<!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"><title>Mongoose API v3.1.2</title><link href="http://fonts.googleapis.com/css?family=Anonymous+Pro:400,700|Droid+Sans+Mono|Open+Sans:400,700|Linden+Hill|Quattrocento:400,700|News+Cycle:400,700|Antic+Slab|Cabin+Condensed:400,700" rel="stylesheet" type="text/css"><link href="css/default.css" rel="stylesheet" type="text/css"><style>body {
  background: #d8e2d8 url(./images/square_bg.png) fixed;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
  color: #333;
  -webkit-font-smoothing: antialiased;
  -webkit-text-size-adjust: 100%;
  padding: 0;
  margin: 0;
  font-size: 14px;
  line-height: 22px;
}
a {
  color: #800;
  -webkit-transition-property: opacity, -webkit-transform, color, background-color, padding, -webkit-box-shadow;
  -webkit-transition-duration: 0.15s;
  -webkit-transition-timing-function: ease-out;
}
a:hover {
  opacity: 0.8;
}
#wrap {
}
h1 {
  font-family: 'Helvetica Nueue', Helvetica, Arial, FreeSans, sans-serif;
  text-rendering: geometricPrecision;
}
pre {
  background: rgba(255,255,255,.8);
  border: 1px solid #bbb;
  padding:5px;
  border-radius: 3px;
  box-shadow: 1px 3px 6px #ddd;
}
code {
  background: rgba(255,255,255,.8);
  color: #333;
  border-radius: 3px;
  font-size: 13px;
  font-family: Monaco;
}
pre code {
  border: 0 none;
  padding: 1.2em;
  overflow-x: auto;
}
h3 {
  padding: 20px 15px;
  margin-left: -15px;
}
h3 code {
  font-weight: normal;
}
hr {
  height: 1px;
  border: 0 none;
  padding: 0;
  margin: 60px 0;
  background: -webkit-gradient(linear, left top, right top, from(rgba(57, 172, 57, 0.0)), color-stop(0.5, rgba(57, 172, 57, 0.33)), to(rgba(57, 172, 57, 0.0)))
}
.doclinks hr {
  margin: 10px 0;
}
li {
  list-style: square;
}
#header {
  padding-top: 22px;
  padding-bottom: 25px;
  text-transform: lowercase;
}
#header h1 {
  margin-top: 0;
  margin-bottom: 0;
}
#header h1 a {
  text-decoration: none;
}
#header .mongoose {
  font-size: 50px;
  font-weight: 100;
  color: #fff;
  text-shadow: 6px 4px 5px #777, -2px 0px 2px white;
  letter-spacing: -7px;
}
#links {
  position: fixed;
  top: 0;
  left: 0;
  bottom: 0;
  width: 210px;
  overflow-x: hidden;
  overflow-y: auto;
  padding: 15px 0 30px 20px;
  border-right: 1px solid #ddd;
  background: -webkit-gradient(linear, left top, right top, from(transparent), color-stop(0.92, transparent), color-stop(0.9201, rgba(172,172,172, 0.0)), to(rgba(172,172,172, 0.4))), transparent;
}
#links hr {
  margin: 32px 0;
}
#content {
  padding: 0;
  margin: 0 0 30px 230px;
  overflow-x: hidden;
}
#content .controls {
  padding: 5px 15px 5px 10px;
  position: fixed;
  background: #fff;
  border: 3px solid #eee;
  border-radius: 0 0 12px 0;
  border-width: 0 3px 3px 10px;
  width: 100%;
  bottom: 0;
  opacity: 0.75;
  -webkit-transition-property: opacity;
  -webkit-transition-duration: 0.15s;
  -webkit-transition-timing-function: ease-out;
}
#content .controls:hover {
  opacity: .9;
}
#content p {
  word-wrap: break-word;
}
#content > ul {
  margin: 0;
  padding: 0;
}
.private {
  display: none;
}
.section {
  font-size: 15px;
}
.doclinks li.private a:before,
.doclinks .module.private a:before,
.doclinks item.private a:before {
  content: "p";
  background: #333;
  color: #fff;
  font-size: 11px;
  line-height: 15px;
  font-weight: normal;
  padding: 0 2px;
  border-radius: 3px;
  border: 1px solid #333;
  display: inline-block;
  margin-right: 5px;
}
#content .private h3:after {
  content: "private";
  background: #333;
  color: #fff;
  font-size: 11px;
  line-height: 15px;
  font-weight: normal;
  padding: 0 2px;
  border-radius: 3px;
  border: 1px solid #333;
  display: inline-block;
  margin-left: 5px;
}
.module {
  list-style: none;
  padding: 30px 0 30px 30px;
  border-color: #eee;
  border-width: 9px 10px;
  border-style: solid;
  background-color: #fff;
}
.module > * {
  max-width: 700px;
}
.item:last-child {
  margin-bottom: 90px;
}
.item:last-child > hr {
  display: none;
}
.item h3 a {
  color: #333;
  text-decoration: none;
}
.property h3 span {
  color: #444;
}
.description {
  margin-top: 25px;
}
.sourcecode {
  display: none;
}
.showcode {
  font-size: 12px;
  cursor: pointer;
  display: none;
}
.load .showcode {
  display: block;
}
.types a {
  text-decoration: none;
}
@media only screen and (device-width: 768px) {

}
@media only screen and (max-width: 480px) {
  #forkbanner { display: none }
  #header .mongoose {
    font-size: 65px;
    text-align: center;
  }
  #links {
    position: static;
    width: auto;
    border: 0 none;
    border-right: 0 none;
    border-bottom: 1px solid #ddd;
    background: -webkit-gradient(linear, left top, left bottom, from(transparent), color-stop(0.92, transparent), color-stop(0.9201, rgba(172,172,172, 0.0)), to(rgba(172,172,172, 0.4))), transparent;
    padding: 15px 0;
  }
  #links hr {
    display: none;
  }
  #links, #links ul, #links li { -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; }
  #links ul { padding: 0 10px 0 0; }
  #links li {
    list-style: none;
    display: inline-block;
    width: 25%;
    text-align: center;
  }
  #links .home, #links .support, #links .fork {
    display: none;
  }
  .doclinks {
    display: none;
  }
  #content { margin-left: 0; }
  .module {
    padding-left: 5px;
    border-width: 3px;
  }
  .controls { display: none; }
}</style></head><body class="api"><a id="forkbanner" href="http://github.com/learnboost/mongoose"><img style="position: absolute; top: 0; right: 0; border: 0;" src="https://s3.amazonaws.com/github/ribbons/forkme_right_gray_6d6d6d.png" alt="Fork me on GitHub"></a><div id="links"><div id="header"><h1><a href="../index.html"><div class="mongoose">Mongoose</div></a></h1></div><ul><li class="home"><a href="../index.html">home</a></li><li class="faq"><a href="./faq.html">FAQ</a></li><li class="plugins"><a href="http://plugins.mongoosejs.com">plugins</a></li><li class="changelog"><a href="http://github.com/learnboost/mongoose/tree/master/History.md">change log</a></li><li class="support"><a href="../index.html#support">support</a></li><li class="fork"><a href="http://github.com/learnboost/mongoose">fork</a></li><li class="guide"><a href="./guide.html">guide</a></li><li class="api"><a href="./api.html">api docs</a></li><li class="quickstart"><a href="./index.html">quick start</a></li><li class="contrib"><a href="http://github.com/learnboost/mongoose/contributors">contributors</a></li><li class="prior"><a href="./prior.html">prior releases</a></li></ul><hr><div class="doclinks"><div class="file "><a href="#index-js" class="section">index.js</a><ul><li class=""><a href="#index_Mongoose">Mongoose</a></li><li class=""><a href="#index_Mongoose-set">set</a></li><li class=""><a href="#index_Mongoose-get">get</a></li><li class=""><a href="#index_Mongoose-createConnection">createConnection</a></li><li class=""><a href="#index_Mongoose-connect">connect</a></li><li class=""><a href="#index_Mongoose-disconnect">disconnect</a></li><li class=""><a href="#index_Mongoose-model">model</a></li><li class=""><a href="#index_Mongoose-plugin">plugin</a></li><li class=""><a href="#index_module-exports">exports</a></li><li class=""><a href="#index_mongoose-Collection">Collection</a></li><li class=""><a href="#index_mongoose-Connection">Connection</a></li><li class=""><a href="#index_mongoose-version">version</a></li><li class=""><a href="#index_mongoose-Mongoose">Mongoose</a></li><li class=""><a href="#index_mongoose-Schema">Schema</a></li><li class=""><a href="#index_mongoose-SchemaType">SchemaType</a></li><li class=""><a href="#index_mongoose-SchemaTypes">SchemaTypes</a></li><li class=""><a href="#index_mongoose-VirtualType">VirtualType</a></li><li class=""><a href="#index_mongoose-Types">Types</a></li><li class=""><a href="#index_mongoose-Query">Query</a></li><li class=""><a href="#index_mongoose-Promise">Promise</a></li><li class=""><a href="#index_mongoose-Model">Model</a></li><li class=""><a href="#index_mongoose-Document">Document</a></li><li class=""><a href="#index_mongoose-Error">Error</a></li><li class=""><a href="#index_mongoose-mongo">mongo</a></li><li class=""><a href="#index_Mongoose-connection">connection</a></li></ul></div><div class="file "><a href="#collection-js" class="section">collection.js</a><ul><li class=""><a href="#collection_Collection">Collection</a></li><li class="private"><a href="#collection_Collection-onOpen">onOpen</a></li><li class="private"><a href="#collection_Collection-onClose">onClose</a></li><li class="private"><a href="#collection_Collection-addQueue">addQueue</a></li><li class="private"><a href="#collection_Collection-doQueue">doQueue</a></li><li class=""><a href="#collection_Collection-ensureIndex">ensureIndex</a></li><li class=""><a href="#collection_Collection-findAndModify">findAndModify</a></li><li class=""><a href="#collection_Collection-findOne">findOne</a></li><li class=""><a href="#collection_Collection-find">find</a></li><li class=""><a href="#collection_Collection-insert">insert</a></li><li class=""><a href="#collection_Collection-save">save</a></li><li class=""><a href="#collection_Collection-update">update</a></li><li class=""><a href="#collection_Collection-getIndexes">getIndexes</a></li><li class=""><a href="#collection_Collection-mapReduce">mapReduce</a></li><li class=""><a href="#collection_Collection-conn">conn</a></li><li class=""><a href="#collection_Collection-name">name</a></li></ul></div><div class="file "><a href="#connection-js" class="section">connection.js</a><ul><li class=""><a href="#connection_Connection">Connection</a></li><li class=""><a href="#connection_Connection-open">open</a></li><li class=""><a href="#connection_Connection-openSet">openSet</a></li><li class="private"><a href="#connection_Connection-error">error</a></li><li class="private"><a href="#connection_Connection-_open">_open</a></li><li class="private"><a href="#connection_Connection-onOpen">onOpen</a></li><li class=""><a href="#connection_Connection-close">close</a></li><li class="private"><a href="#connection_Connection-onClose">onClose</a></li><li class=""><a href="#connection_Connection-collection">collection</a></li><li class=""><a href="#connection_Connection-model">model</a></li><li class=""><a href="#connection_Connection-setProfiling">setProfiling</a></li><li class="private"><a href="#connection_Connection-defaultOptions">defaultOptions</a></li><li class=""><a href="#connection_Connection-db">db</a></li><li class=""><a href="#connection_Connection-collections">collections</a></li><li class=""><a href="#connection_Connection-readyState">readyState</a></li></ul></div><div class="file "><a href="#document-js" class="section">document.js</a><ul><li class="private"><a href="#document_Document">Document</a></li><li class="private"><a href="#document_Document-_buildDoc">_buildDoc</a></li><li class="private"><a href="#document_Document-init">init</a></li><li class="private"><a href="#document_Document-_storeShard">_storeShard</a></li><li class=""><a href="#document_Document-update">update</a></li><li class=""><a href="#document_Document-set">set</a></li><li class="private"><a href="#document_Document-_set">_set</a></li><li class="private"><a href="#document_Document-getValue">getValue</a></li><li class="private"><a href="#document_Document-setValue">setValue</a></li><li class=""><a href="#document_Document-get">get</a></li><li class="private"><a href="#document_Document-_path">_path</a></li><li class=""><a href="#document_Document-markModified">markModified</a></li><li class="private"><a href="#document_Document-try">try</a></li><li class=""><a href="#document_Document-modifiedPaths">modifiedPaths</a></li><li class=""><a href="#document_Document-isModified">isModified</a></li><li class=""><a href="#document_Document-isDirectModified">isDirectModified</a></li><li class=""><a href="#document_Document-isInit">isInit</a></li><li class=""><a href="#document_Document-isSelected">isSelected</a></li><li class=""><a href="#document_Document-validate">validate</a></li><li class=""><a href="#document_Document-invalidate">invalidate</a></li><li class="private"><a href="#document_Document-_reset">_reset</a></li><li class="private"><a href="#document_Document-_dirty">_dirty</a></li><li class="private"><a href="#document_Document-_setSchema">_setSchema</a></li><li class="private"><a href="#document_Document-_registerHooks">_registerHooks</a></li><li class="private"><a href="#document_Document-_error">_error</a></li><li class="private"><a href="#document_Document-_doQueue">_doQueue</a></li><li class=""><a href="#document_Document-toObject">toObject</a></li><li class=""><a href="#document_Document-toJSON">toJSON</a></li><li class=""><a href="#document_Document-inspect">inspect</a></li><li class=""><a href="#document_Document-toString">toString</a></li><li class=""><a href="#document_Document-equals">equals</a></li><li class=""><a href="#document_Document-errors">errors</a></li><li class=""><a href="#document_Document-id">id</a></li><li class=""><a href="#document_Document-isNew">isNew</a></li><li class=""><a href="#document_Document-schema">schema</a></li></ul></div><div class="file "><a href="#drivers-node-mongodb-native-collection-js" class="section">drivers/node-mongodb-native/collection.js</a><ul><li class="private"><a href="#drivers_node-mongodb-native_collection_NativeCollection">NativeCollection</a></li><li class="private"><a href="#drivers_node-mongodb-native_collection_NativeCollection-onOpen">onOpen</a></li><li class="private"><a href="#drivers_node-mongodb-native_collection_NativeCollection-onClose">onClose</a></li><li class=""><a href="#drivers_node-mongodb-native_collection_NativeCollection-getIndexes">getIndexes</a></li></ul></div><div class="file private"><a href="#drivers-node-mongodb-native-connection-js" class="section">drivers/node-mongodb-native/connection.js</a><ul><li class="private"><a href="#drivers_node-mongodb-native_connection_NativeConnection">NativeConnection</a></li><li class="private"><a href="#drivers_node-mongodb-native_connection_NativeConnection-doOpen">doOpen</a></li><li class="private"><a href="#drivers_node-mongodb-native_connection_NativeConnection-doOpenSet">doOpenSet</a></li><li class="private"><a href="#drivers_node-mongodb-native_connection_NativeConnection-doClose">doClose</a></li></ul></div><div class="file private"><a href="#error-js" class="section">error.js</a><ul><li class="private"><a href="#error_MongooseError">MongooseError</a></li></ul></div><div class="file private"><a href="#errors-cast-js" class="section">errors/cast.js</a><ul><li class="private"><a href="#errors_cast_CastError">CastError</a></li></ul></div><div class="file private"><a href="#errors-document-js" class="section">errors/document.js</a><ul><li class="private"><a href="#errors_document_DocumentError">DocumentError</a></li></ul></div><div class="file "><a href="#errors-validation-js" class="section">errors/validation.js</a><ul><li class="private"><a href="#errors_validation_ValidationError">ValidationError</a></li><li class=""><a href="#errors_validation_ValidationError-toString">toString</a></li></ul></div><div class="file private"><a href="#errors-validator-js" class="section">errors/validator.js</a><ul><li class="private"><a href="#errors_validator_ValidatorError">ValidatorError</a></li></ul></div><div class="file "><a href="#model-js" class="section">model.js</a><ul><li class=""><a href="#model_Model">Model</a></li><li class="private"><a href="#model_Model-_getPopulationKeys">_getPopulationKeys</a></li><li class="private"><a href="#model_Model-_populate">_populate</a></li><li class="private"><a href="#model_Model-init">init</a></li><li class=""><a href="#model_Model-save">save</a></li><li class="private"><a href="#model_Model-_delta">_delta</a></li><li class="private"><a href="#model_Model-_version">_version</a></li><li class=""><a href="#model_Model-increment">increment</a></li><li class="private"><a href="#model_Model-_where">_where</a></li><li class=""><a href="#model_Model-remove">remove</a></li><li class="private"><a href="#model_Model-_registerHooks">_registerHooks</a></li><li class=""><a href="#model_Model-model">model</a></li><li class=""><a href="#model_Model-%24where">$where</a></li><li class="private"><a href="#model_Model-init">init</a></li><li class=""><a href="#model_Model-ensureIndexes">ensureIndexes</a></li><li class=""><a href="#model_Model-remove">remove</a></li><li class=""><a href="#model_Model-find">find</a></li><li class="private"><a href="#model_Model-_applyNamedScope">_applyNamedScope</a></li><li class=""><a href="#model_Model-findById">findById</a></li><li class=""><a href="#model_Model-findOne">findOne</a></li><li class=""><a href="#model_Model-count">count</a></li><li class=""><a href="#model_Model-distinct">distinct</a></li><li class=""><a href="#model_Model-where">where</a></li><li class=""><a href="#model_Model-findOneAndUpdate">findOneAndUpdate</a></li><li class=""><a href="#model_Model-findByIdAndUpdate">findByIdAndUpdate</a></li><li class=""><a href="#model_Model-findOneAndRemove">findOneAndRemove</a></li><li class=""><a href="#model_Model-findByIdAndRemove">findByIdAndRemove</a></li><li class=""><a href="#model_Model-create">create</a></li><li class=""><a href="#model_Model-update">update</a></li><li class=""><a href="#model_Model-mapReduce">mapReduce</a></li><li class=""><a href="#model_Model-aggregate">aggregate</a></li><li class=""><a href="#model_Model-base">base</a></li><li class=""><a href="#model_Model-collection">collection</a></li><li class=""><a href="#model_Model-db">db</a></li><li class=""><a href="#model_Model-schema">schema</a></li><li class=""><a href="#model_Model-modelName">modelName</a></li><li class=""><a href="#model_Model-collection">collection</a></li><li class=""><a href="#model_Model-db">db</a></li></ul></div><div class="file private"><a href="#namedscope-js" class="section">namedscope.js</a><ul><li class="private"><a href="#namedscope_NamedScope-decorate">decorate</a></li></ul></div><div class="file "><a href="#promise-js" class="section">promise.js</a><ul><li class=""><a href="#promise_Promise">Promise</a></li><li class=""><a href="#promise_Promise-on">on</a></li><li class="private"><a href="#promise_Promise-emit">emit</a></li><li class=""><a href="#promise_Promise-complete">complete</a></li><li class=""><a href="#promise_Promise-error">error</a></li><li class=""><a href="#promise_Promise-addCallback">addCallback</a></li><li class=""><a href="#promise_Promise-addErrback">addErrback</a></li><li class=""><a href="#promise_Promise-addBack">addBack</a></li><li class=""><a href="#promise_Promise-resolve">resolve</a></li></ul></div><div class="file "><a href="#query-js" class="section">query.js</a><ul><li class=""><a href="#query_Query">Query</a></li><li class=""><a href="#query_Query-setOptions">setOptions</a></li><li class="private"><a href="#query_Query-bind">bind</a></li><li class=""><a href="#query_Query-exec">exec</a></li><li class=""><a href="#query_Query-find">find</a></li><li class=""><a href="#query_Query-cast">cast</a></li><li class="private"><a href="#query_Query-_optionsForExec">_optionsForExec</a></li><li class="private"><a href="#query_Query-_applyPaths">_applyPaths</a></li><li class=""><a href="#query_Query-%24where">$where</a></li><li class=""><a href="#query_Query-where">where</a></li><li class=""><a href="#query_Query-equals">equals</a></li><li class=""><a href="#query_Query-or">or</a></li><li class=""><a href="#query_Query-nor">nor</a></li><li class=""><a href="#query_Query-gt">gt</a></li><li class=""><a href="#query_Query-gte">gte</a></li><li class=""><a href="#query_Query-lt">lt</a></li><li class=""><a href="#query_Query-lte">lte</a></li><li class=""><a href="#query_Query-ne">ne</a></li><li class=""><a href="#query_Query-in">in</a></li><li class=""><a href="#query_Query-nin">nin</a></li><li class=""><a href="#query_Query-all">all</a></li><li class=""><a href="#query_Query-size">size</a></li><li class=""><a href="#query_Query-regex">regex</a></li><li class=""><a href="#query_Query-maxDistance">maxDistance</a></li><li class=""><a href="#query_Query-near">near</a></li><li class=""><a href="#query_Query-nearSphere">nearSphere</a></li><li class=""><a href="#query_Query-mod">mod</a></li><li class=""><a href="#query_Query-exists">exists</a></li><li class=""><a href="#query_Query-elemMatch">elemMatch</a></li><li class=""><a href="#query_Query-box">box</a></li><li class=""><a href="#query_Query-center">center</a></li><li class=""><a href="#query_Query-centerSphere">centerSphere</a></li><li class=""><a href="#query_Query-polygon">polygon</a></li><li class=""><a href="#query_Query-select">select</a></li><li class=""><a href="#query_Query-slice">slice</a></li><li class=""><a href="#query_Query-sort">sort</a></li><li class=""><a href="#query_Query-limit">limit</a></li><li class=""><a href="#query_Query-skip">skip</a></li><li class=""><a href="#query_Query-maxscan">maxscan</a></li><li class=""><a href="#query_Query-batchSize">batchSize</a></li><li class=""><a href="#query_Query-comment">comment</a></li><li class=""><a href="#query_Query-snapshot">snapshot</a></li><li class=""><a href="#query_Query-hint">hint</a></li><li class=""><a href="#query_Query-slaveOk">slaveOk</a></li><li class=""><a href="#query_Query-read">read</a></li><li class=""><a href="#query_Query-lean">lean</a></li><li class=""><a href="#query_Query-tailable">tailable</a></li><li class="private"><a href="#query_Query-execFind">execFind</a></li><li class=""><a href="#query_Query-findOne">findOne</a></li><li class=""><a href="#query_Query-count">count</a></li><li class=""><a href="#query_Query-distinct">distinct</a></li><li class=""><a href="#query_Query-update">update</a></li><li class="private"><a href="#query_Query-_castUpdate">_castUpdate</a></li><li class="private"><a href="#query_Query-_walkUpdatePath">_walkUpdatePath</a></li><li class="private"><a href="#query_Query-_castUpdateVal">_castUpdateVal</a></li><li class="private"><a href="#query_Query-_getSchema">_getSchema</a></li><li class="private"><a href="#query_Query-_castFields">_castFields</a></li><li class=""><a href="#query_Query-remove">remove</a></li><li class=""><a href="#query_Query-findOneAndUpdate">findOneAndUpdate</a></li><li class=""><a href="#query_Query-findOneAndRemove">findOneAndRemove</a></li><li class="private"><a href="#query_Query-_findAndModify">_findAndModify</a></li><li class=""><a href="#query_Query-populate">populate</a></li><li class=""><a href="#query_Query-stream">stream</a></li><li class=""><a href="#query_Query-within">within</a></li></ul></div><div class="file "><a href="#querystream-js" class="section">querystream.js</a><ul><li class=""><a href="#querystream_QueryStream">QueryStream</a></li><li class="private"><a href="#querystream_QueryStream-_init">_init</a></li><li class="private"><a href="#querystream_QueryStream-_next">_next</a></li><li class="private"><a href="#querystream_QueryStream-__next">__next</a></li><li class="private"><a href="#querystream_QueryStream-_onNextObject">_onNextObject</a></li><li class=""><a href="#querystream_QueryStream-pause">pause</a></li><li class=""><a href="#querystream_QueryStream-resume">resume</a></li><li class=""><a href="#querystream_QueryStream-destroy">destroy</a></li><li class=""><a href="#querystream_QueryStream-pipe">pipe</a></li><li class=""><a href="#querystream_QueryStream-paused">paused</a></li><li class=""><a href="#querystream_QueryStream-readable">readable</a></li></ul></div><div class="file private"><a href="#schema-array-js" class="section">schema/array.js</a><ul><li class="private"><a href="#schema_array_SchemaArray">SchemaArray</a></li><li class="private"><a href="#schema_array_SchemaArray-checkRequired">checkRequired</a></li><li class="private"><a href="#schema_array_SchemaArray-applyGetters">applyGetters</a></li><li class="private"><a href="#schema_array_SchemaArray-cast">cast</a></li><li class="private"><a href="#schema_array_SchemaArray-castForQuery">castForQuery</a></li></ul></div><div class="file private"><a href="#schema-boolean-js" class="section">schema/boolean.js</a><ul><li class="private"><a href="#schema_boolean_SchemaBoolean">SchemaBoolean</a></li><li class="private"><a href="#schema_boolean_SchemaBoolean-checkRequired">checkRequired</a></li><li class="private"><a href="#schema_boolean_SchemaBoolean-cast">cast</a></li><li class="private"><a href="#schema_boolean_SchemaBoolean-castForQuery">castForQuery</a></li></ul></div><div class="file private"><a href="#schema-buffer-js" class="section">schema/buffer.js</a><ul><li class="private"><a href="#schema_buffer_SchemaBuffer">SchemaBuffer</a></li><li class="private"><a href="#schema_buffer_SchemaBuffer-checkRequired">checkRequired</a></li><li class="private"><a href="#schema_buffer_SchemaBuffer-cast">cast</a></li><li class="private"><a href="#schema_buffer_SchemaBuffer-castForQuery">castForQuery</a></li></ul></div><div class="file private"><a href="#schema-date-js" class="section">schema/date.js</a><ul><li class="private"><a href="#schema_date_SchemaDate">SchemaDate</a></li><li class="private"><a href="#schema_date_SchemaDate-checkRequired">checkRequired</a></li><li class="private"><a href="#schema_date_SchemaDate-cast">cast</a></li><li class="private"><a href="#schema_date_SchemaDate-castForQuery">castForQuery</a></li></ul></div><div class="file private"><a href="#schema-documentarray-js" class="section">schema/documentarray.js</a><ul><li class="private"><a href="#schema_documentarray_DocumentArray">DocumentArray</a></li><li class="private"><a href="#schema_documentarray_DocumentArray-doValidate">doValidate</a></li><li class="private"><a href="#schema_documentarray_DocumentArray-cast">cast</a></li></ul></div><div class="file private"><a href="#schema-mixed-js" class="section">schema/mixed.js</a><ul><li class="private"><a href="#schema_mixed_Mixed">Mixed</a></li><li class="private"><a href="#schema_mixed_Mixed-checkRequired">checkRequired</a></li><li class="private"><a href="#schema_mixed_Mixed-cast">cast</a></li><li class="private"><a href="#schema_mixed_Mixed-castForQuery">castForQuery</a></li></ul></div><div class="file "><a href="#schema-number-js" class="section">schema/number.js</a><ul><li class="private"><a href="#schema_number_SchemaNumber">SchemaNumber</a></li><li class="private"><a href="#schema_number_SchemaNumber-checkRequired">checkRequired</a></li><li class=""><a href="#schema_number_SchemaNumber-min">min</a></li><li class=""><a href="#schema_number_SchemaNumber-max">max</a></li><li class="private"><a href="#schema_number_SchemaNumber-cast">cast</a></li><li class="private"><a href="#schema_number_SchemaNumber-castForQuery">castForQuery</a></li></ul></div><div class="file private"><a href="#schema-objectid-js" class="section">schema/objectid.js</a><ul><li class="private"><a href="#schema_objectid_ObjectId">ObjectId</a></li><li class="private"><a href="#schema_objectid_ObjectId-checkRequired">checkRequired</a></li><li class="private"><a href="#schema_objectid_ObjectId-cast">cast</a></li><li class="private"><a href="#schema_objectid_ObjectId-castForQuery">castForQuery</a></li><li class="private"><a href="#schema_objectid_ObjectId-auto">auto</a></li></ul></div><div class="file "><a href="#schema-string-js" class="section">schema/string.js</a><ul><li class="private"><a href="#schema_string_SchemaString">SchemaString</a></li><li class=""><a href="#schema_string_SchemaString-enum">enum</a></li><li class=""><a href="#schema_string_SchemaString-lowercase">lowercase</a></li><li class=""><a href="#schema_string_SchemaString-uppercase">uppercase</a></li><li class=""><a href="#schema_string_SchemaString-trim">trim</a></li><li class=""><a href="#schema_string_SchemaString-match">match</a></li><li class="private"><a href="#schema_string_SchemaString-checkRequired">checkRequired</a></li><li class="private"><a href="#schema_string_SchemaString-cast">cast</a></li><li class="private"><a href="#schema_string_SchemaString-castForQuery">castForQuery</a></li></ul></div><div class="file "><a href="#schema-js" class="section">schema.js</a><ul><li class=""><a href="#schema_Schema">Schema</a></li><li class="private"><a href="#schema_Schema-defaultOptions">defaultOptions</a></li><li class=""><a href="#schema_Schema-add">add</a></li><li class=""><a href="#schema_Schema-path">path</a></li><li class=""><a href="#schema_Schema-eachPath">eachPath</a></li><li class=""><a href="#schema_Schema-requiredPaths">requiredPaths</a></li><li class=""><a href="#schema_Schema-pathType">pathType</a></li><li class="private"><a href="#schema_Schema-queue">queue</a></li><li class=""><a href="#schema_Schema-pre">pre</a></li><li class=""><a href="#schema_Schema-post">post</a></li><li class=""><a href="#schema_Schema-plugin">plugin</a></li><li class=""><a href="#schema_Schema-method">method</a></li><li class=""><a href="#schema_Schema-static">static</a></li><li class=""><a href="#schema_Schema-index">index</a></li><li class=""><a href="#schema_Schema-set">set</a></li><li class=""><a href="#schema_Schema-indexes">indexes</a></li><li class=""><a href="#schema_Schema-virtual">virtual</a></li><li class=""><a href="#schema_Schema-virtualpath">virtualpath</a></li><li class="private"><a href="#schema_Schema-namedScope">namedScope</a></li><li class=""><a href="#schema_Schema-reserved">reserved</a></li><li class="private"><a href="#schema_Schema-interpretAsType">interpretAsType</a></li><li class=""><a href="#schema_Schema-Types">Types</a></li><li class="private"><a href="#schema_Schema-tree">tree</a></li><li class="private"><a href="#schema_Schema-paths">paths</a></li></ul></div><div class="file private"><a href="#schemadefault-js" class="section">schemadefault.js</a><ul><li class="private"><a href="#schemadefault_exports-system-profile">system.profile</a></li></ul></div><div class="file "><a href="#schematype-js" class="section">schematype.js</a><ul><li class=""><a href="#schematype_SchemaType">SchemaType</a></li><li class=""><a href="#schematype_SchemaType-default">default</a></li><li class=""><a href="#schematype_SchemaType-index">index</a></li><li class=""><a href="#schematype_SchemaType-unique">unique</a></li><li class=""><a href="#schematype_SchemaType-sparse">sparse</a></li><li class=""><a href="#schematype_SchemaType-expires">expires</a></li><li class=""><a href="#schematype_SchemaType-set">set</a></li><li class=""><a href="#schematype_SchemaType-get">get</a></li><li class=""><a href="#schematype_SchemaType-validate">validate</a></li><li class=""><a href="#schematype_SchemaType-required">required</a></li><li class="private"><a href="#schematype_SchemaType-getDefault">getDefault</a></li><li class="private"><a href="#schematype_SchemaType-applySetters">applySetters</a></li><li class="private"><a href="#schematype_SchemaType-applyGetters">applyGetters</a></li><li class=""><a href="#schematype_SchemaType-select">select</a></li><li class="private"><a href="#schematype_SchemaType-doValidate">doValidate</a></li><li class="private"><a href="#schematype_SchemaType-_isRef">_isRef</a></li></ul></div><div class="file "><a href="#types-array-js" class="section">types/array.js</a><ul><li class="private"><a href="#types_array_MongooseArray">MongooseArray</a></li><li class="private"><a href="#types_array_MongooseArray-_cast">_cast</a></li><li class="private"><a href="#types_array_MongooseArray-_markModified">_markModified</a></li><li class="private"><a href="#types_array_MongooseArray-_registerAtomic">_registerAtomic</a></li><li class="private"><a href="#types_array_MongooseArray-hasAtomics">hasAtomics</a></li><li class=""><a href="#types_array_MongooseArray-push">push</a></li><li class=""><a href="#types_array_MongooseArray-nonAtomicPush">nonAtomicPush</a></li><li class=""><a href="#types_array_MongooseArray-%24pop">$pop</a></li><li class=""><a href="#types_array_MongooseArray-pop">pop</a></li><li class=""><a href="#types_array_MongooseArray-%24shift">$shift</a></li><li class=""><a href="#types_array_MongooseArray-shift">shift</a></li><li class=""><a href="#types_array_MongooseArray-remove">remove</a></li><li class=""><a href="#types_array_MongooseArray-pull">pull</a></li><li class=""><a href="#types_array_MongooseArray-splice">splice</a></li><li class=""><a href="#types_array_MongooseArray-unshift">unshift</a></li><li class=""><a href="#types_array_MongooseArray-sort">sort</a></li><li class=""><a href="#types_array_MongooseArray-addToSet">addToSet</a></li><li class=""><a href="#types_array_MongooseArray-toObject">toObject</a></li><li class=""><a href="#types_array_MongooseArray-inspect">inspect</a></li><li class=""><a href="#types_array_MongooseArray-indexOf">indexOf</a></li><li class="private"><a href="#types_array_MongooseArray-_parent">_parent</a></li><li class="private"><a href="#types_array_MongooseArray-_atomics">_atomics</a></li></ul></div><div class="file "><a href="#types-buffer-js" class="section">types/buffer.js</a><ul><li class="private"><a href="#types_buffer_MongooseBuffer">MongooseBuffer</a></li><li class="private"><a href="#types_buffer_MongooseBuffer-_markModified">_markModified</a></li><li class=""><a href="#types_buffer_MongooseBuffer-write">write</a></li><li class=""><a href="#types_buffer_MongooseBuffer-copy">copy</a></li><li class=""><a href="#types_buffer_MongooseBuffer-toObject">toObject</a></li><li class="private"><a href="#types_buffer_MongooseBuffer-_parent">_parent</a></li></ul></div><div class="file "><a href="#types-documentarray-js" class="section">types/documentarray.js</a><ul><li class="private"><a href="#types_documentarray_MongooseDocumentArray">MongooseDocumentArray</a></li><li class="private"><a href="#types_documentarray_MongooseDocumentArray-_cast">_cast</a></li><li class=""><a href="#types_documentarray_MongooseDocumentArray-id">id</a></li><li class=""><a href="#types_documentarray_MongooseDocumentArray-toObject">toObject</a></li><li class=""><a href="#types_documentarray_MongooseDocumentArray-inspect">inspect</a></li><li class=""><a href="#types_documentarray_MongooseDocumentArray-create">create</a></li><li class="private"><a href="#types_documentarray_MongooseDocumentArray-notify">notify</a></li></ul></div><div class="file "><a href="#types-embedded-js" class="section">types/embedded.js</a><ul><li class="private"><a href="#types_embedded_EmbeddedDocument">EmbeddedDocument</a></li><li class=""><a href="#types_embedded_EmbeddedDocument-markModified">markModified</a></li><li class="private"><a href="#types_embedded_EmbeddedDocument-save">save</a></li><li class=""><a href="#types_embedded_EmbeddedDocument-remove">remove</a></li><li class="private"><a href="#types_embedded_EmbeddedDocument-update">update</a></li><li class=""><a href="#types_embedded_EmbeddedDocument-inspect">inspect</a></li><li class=""><a href="#types_embedded_EmbeddedDocument-invalidate">invalidate</a></li><li class=""><a href="#types_embedded_EmbeddedDocument-ownerDocument">ownerDocument</a></li><li class=""><a href="#types_embedded_EmbeddedDocument-parent">parent</a></li><li class=""><a href="#types_embedded_EmbeddedDocument-parentArray">parentArray</a></li></ul></div><div class="file "><a href="#types-objectid-js" class="section">types/objectid.js</a><ul><li class=""><a href="#types_objectid_ObjectId">ObjectId</a></li><li class="private"><a href="#types_objectid_ObjectId-fromString">fromString</a></li><li class="private"><a href="#types_objectid_ObjectId-toString">toString</a></li></ul></div><div class="file "><a href="#utils-js" class="section">utils.js</a><ul><li class="private"><a href="#utils_exports-toCollectionName">toCollectionName</a></li><li class=""><a href="#utils_exports-pluralization">pluralization</a></li><li class=""><a href="#utils_exports-uncountables">uncountables</a></li><li class="private"><a href="#utils_exports-deepEqual">deepEqual</a></li><li class="private"><a href="#utils_exports-clone">clone</a></li><li class="private"><a href="#utils_exports-options">options</a></li><li class="private"><a href="#utils_exports-random">random</a></li><li class="private"><a href="#utils_exports-merge">merge</a></li><li class="private"><a href="#utils_exports-args">args</a></li><li class="private"><a href="#utils_exports-tick">tick</a></li><li class="private"><a href="#utils_exports-isMongooseObject">isMongooseObject</a></li><li class="private"><a href="#utils_exports-expires">expires</a></li></ul></div><div class="file "><a href="#virtualtype-js" class="section">virtualtype.js</a><ul><li class=""><a href="#virtualtype_VirtualType">VirtualType</a></li><li class=""><a href="#virtualtype_VirtualType-get">get</a></li><li class=""><a href="#virtualtype_VirtualType-set">set</a></li><li class=""><a href="#virtualtype_VirtualType-applyGetters">applyGetters</a></li><li class=""><a href="#virtualtype_VirtualType-applySetters">applySetters</a></li></ul></div></div></div><div id="content"><div class="controls"><label><input type="checkbox">private</label></div><ul><li class="module "><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/index.js" id="index-js">index.js</a><div class="item method public"><h3 id="index_Mongoose"><a href="#index_Mongoose">Mongoose()</a></h3><p>Mongoose constructor.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">Mongoose</span> <span class="params">()</span> {</span>
  <span class="keyword">this</span>.connections = [];
  <span class="keyword">this</span>.plugins = [];
  <span class="keyword">this</span>.models = {};
  <span class="keyword">this</span>.modelSchemas = {};
  <span class="keyword">this</span>.options = {};
  <span class="keyword">this</span>.createConnection(); <span class="comment">// default connection</span>
};</code></pre></div><div class="description"><p>The exports object of the <code>mongoose</code> module is an instance of this class.<br />Most apps will only use this one instance.</p></div><hr class=""></div><div class="item method public"><h3 id="index_Mongoose-set"><a href="#index_Mongoose-set">Mongoose#set(<code>key</code>, <code>value</code>)</a></h3><p>Sets mongoose options</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Mongoose.prototype.set = <span class="function"><span class="keyword">function</span> <span class="params">(key, value)</span> {</span>
  <span class="keyword">if</span> (arguments.length == <span class="number">1</span>)
    <span class="keyword">return</span> <span class="keyword">this</span>.options[key];
  <span class="keyword">this</span>.options[key] = value;
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>key</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>value</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code>mongoose.set(<span class="string">'test'</span>, value) <span class="comment">// sets the 'test' option to `value`</span></code></pre></div><hr class=""></div><div class="item method public"><h3 id="index_Mongoose-get"><a href="#index_Mongoose-get">Mongoose#get(<code>key</code>)</a></h3><p>Gets mongoose options</p><div class="params"><h4>Parameters:</h4><ul><li><code>key</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code>mongoose.get(<span class="string">'test'</span>) <span class="comment">// returns the 'test' value</span></code></pre></div><hr class=""></div><div class="item method public"><h3 id="index_Mongoose-createConnection"><a href="#index_Mongoose-createConnection">Mongoose#createConnection(<code>[uri]</code>)</a></h3><p>Creates a Connection instance.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Mongoose.prototype.createConnection = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">var</span> conn = <span class="keyword">new</span> Connection(<span class="keyword">this</span>);
  <span class="keyword">this</span>.connections.push(conn);

  <span class="keyword">if</span> (arguments.length) {
    <span class="keyword">if</span> (rgxReplSet.test(arguments[<span class="number">0</span>])) {
      conn.openSet.apply(conn, arguments);
    } <span class="keyword">else</span> {
      conn.open.apply(conn, arguments);
    }
  }

  <span class="keyword">return</span> conn;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>[uri]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>a mongodb:// URI</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#connection_Connection">Connection</a>&gt; </span><span>the created Connection object</span></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code><span class="comment">// with mongodb:// URI</span>
db = mongoose.createConnection(<span class="string">'mongodb://localhost:port/database'</span>);

<span class="comment">// replica sets</span>
db = mongoose.createConnection(<span class="string">'mongodb://localhost:port/database,mongodb://anotherhost:port,mongodb://yetanother:port'</span>);

<span class="comment">// with [host, database_name[, port] signature</span>
db = mongoose.createConnection(<span class="string">'localhost'</span>, <span class="string">'database'</span>, port)

<span class="comment">// initialize now, connect later</span>
db = mongoose.createConnection();
db.open(<span class="string">'localhost'</span>, <span class="string">'database'</span>, port);</code></pre></div><hr class=""></div><div class="item method public"><h3 id="index_Mongoose-connect"><a href="#index_Mongoose-connect">Mongoose#connect()</a></h3><p>Opens the default mongoose connection.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Mongoose.prototype.connect = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">var</span> conn = <span class="keyword">this</span>.connection;

  <span class="keyword">if</span> (rgxReplSet.test(arguments[<span class="number">0</span>])) {
    conn.openSet.apply(conn, arguments);
  } <span class="keyword">else</span> {
    conn.open.apply(conn, arguments);
  }

  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#index_Mongoose">Mongoose</a>&gt; </span><span>this</span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="Mongoose#createConnection" title="Mongoose#createConnection">Mongoose#createConnection</a></li></ul></div><div class="description"><p>If arguments are passed, they are proxied to either <a href="#connection_Connection-open">Connection#open</a> or <a href="#connection_Connection-openSet">Connection#openSet</a> appropriately.</p></div><hr class=""></div><div class="item method public"><h3 id="index_Mongoose-disconnect"><a href="#index_Mongoose-disconnect">Mongoose#disconnect(<code>[fn]</code>)</a></h3><p>Disconnects all connections.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Mongoose.prototype.disconnect = <span class="function"><span class="keyword">function</span> <span class="params">(fn)</span> {</span>
  <span class="keyword">var</span> count = <span class="keyword">this</span>.connections.length
    , error

  <span class="keyword">this</span>.connections.forEach(<span class="keyword">function</span>(conn){
    conn.close(<span class="keyword">function</span>(err){
      <span class="keyword">if</span> (error) <span class="keyword">return</span>;

      <span class="keyword">if</span> (err) {
        error = err;
        <span class="keyword">if</span> (fn) <span class="keyword">return</span> fn(err);
        <span class="keyword">throw</span> err;
      }

      <span class="keyword">if</span> (fn)
        --count || fn();
    });
  });
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>[fn]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span>called after all connection close.</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#index_Mongoose">Mongoose</a>&gt; </span><span>this</span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="index_Mongoose-model"><a href="#index_Mongoose-model">Mongoose#model(<code>name</code>, <code>[schema]</code>, <code>[collection]</code>, <code>[skipInit]</code>)</a></h3><p>Defines a model or retrieves it.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Mongoose.prototype.model = function (name, schema, collection, skipInit) {
  // normalize collection
  if (!(schema instanceof Schema)) {
    collection = schema;
    schema = false;
  }

  if ('boolean' === typeof collection) {
    skipInit = collection;
    collection = null;
  }

  // look up models for the collection
  if (!this.modelSchemas[name]) {
    if (!schema &amp;&amp; name in SchemaDefaults) {
      schema = SchemaDefaults[name];
    }

    if (schema) {
      this.modelSchemas[name] = schema;
      for (var i = 0, l = this.plugins.length; i &lt; l; i++) {
        schema.plugin(this.plugins[i][0], this.plugins[i][1]);
      }
    } else {
      throw new Error('Schema hasn\'t been registered for model "' + name + '".
'
                    + 'Use mongoose.model(name, schema)');
    }
  }

  if (!this.models[name]) {
    schema || (schema = this.modelSchemas[name]);
    collection || (collection = schema.set('collection') || format(name));

    var model = Model.compile(name
                        , this.modelSchemas[name]
                        , collection
                        , this.connection
                        , this);

    if (!skipInit) model.init();

    this.models[name] = model;
  }

  return this.models[name];
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>name</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>model name</span></li><li><code>[schema]</code><span class="types"> &lt;<a href="#schema_Schema">Schema</a>&gt; </span><span></span></li><li><code>[collection]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>name (optional, induced from model name)</span></li><li><code>[skipInit]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span>whether to skip initialization (defaults to false)</span></li></ul></div><div class="description"><p>Models defined on the <code>mongoose</code> instance are available to all connection created by the same <code>mongoose</code> instance.</p>

<h4>Example:</h4>

<pre><code><span class="keyword">var</span> mongoose = require(<span class="string">'mongoose'</span>);

<span class="comment">// define an Actor model with this mongoose instance</span>
mongoose.model(<span class="string">'Actor'</span>, <span class="keyword">new</span> Schema({ name: String }));

<span class="comment">// create a new connection</span>
<span class="keyword">var</span> conn = mongoose.createConnection(..);

<span class="comment">// retrieve the Actor model</span>
<span class="keyword">var</span> Actor = conn.model(<span class="string">'Actor'</span>);</code></pre>

<p>When no <code>collection</code> argument is passed, Mongoose produces a collection name by passing the model <code>name</code> to the <a href="#utils.toCollectionName">utils.toCollectionName</a> method. This method pluralizes the name. Collection names can also be declared through schema options.</p>

<h4>Example:</h4>

<pre><code><span class="keyword">var</span> schema = <span class="keyword">new</span> Schema({ name: String });
schema.set(<span class="string">'collection'</span>, <span class="string">'actor'</span>);</code></pre></div><hr class=""></div><div class="item method public"><h3 id="index_Mongoose-plugin"><a href="#index_Mongoose-plugin">Mongoose#plugin(<code>fn</code>, <code>[opts]</code>)</a></h3><p>Declares a global plugin executed on all Schemas.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Mongoose.prototype.plugin = <span class="function"><span class="keyword">function</span> <span class="params">(fn, opts)</span> {</span>
  <span class="keyword">this</span>.plugins.push([fn, opts]);
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>fn</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span>plugin callback</span></li><li><code>[opts]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>optional options</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#index_Mongoose">Mongoose</a>&gt; </span><span>this</span></li></ul></div><div class="description"><p>Equivalent to calling <code>.plugin(fn)</code> on each Schema you create.</p></div><hr class=""></div><div class="item static public"><h3 id="index_module-exports"><a href="#index_module-exports">module.exports</a></h3><p>The exports object is an instance of Mongoose.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">module.exports = exports = <span class="keyword">new</span> Mongoose;
<span class="keyword">var</span> mongoose = module.exports;</code></pre></div><hr class=""></div><div class="item static public"><h3 id="index_mongoose-Collection"><a href="#index_mongoose-Collection">mongoose.Collection</a></h3><p>The Mongoose Collection constructor</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">mongoose.Collection = Collection;</code></pre></div><hr class=""></div><div class="item static public"><h3 id="index_mongoose-Connection"><a href="#index_mongoose-Connection">mongoose.Connection</a></h3><p>The Mongoose Connection constructor</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">mongoose.Connection = Connection;</code></pre></div><hr class=""></div><div class="item static public"><h3 id="index_mongoose-version"><a href="#index_mongoose-version">mongoose.version</a></h3><p>Mongoose version</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">mongoose.version = JSON.parse(
  require(<span class="string">'fs'</span>).readFileSync(__dirname + <span class="string">'/../package.json'</span>, <span class="string">'utf8'</span>)
).version;</code></pre></div><hr class=""></div><div class="item static public"><h3 id="index_mongoose-Mongoose"><a href="#index_mongoose-Mongoose">mongoose.Mongoose</a></h3><p>The Mongoose constructor</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">mongoose.Mongoose = Mongoose;</code></pre></div><p>The exports of the mongoose module is an instance of this class.</p>

<h4>Example:</h4>

<pre><code><span class="keyword">var</span> mongoose = require(<span class="string">'mongoose'</span>);
<span class="keyword">var</span> mongoose2 = <span class="keyword">new</span> mongoose.Mongoose();</code></pre><hr class=""></div><div class="item static public"><h3 id="index_mongoose-Schema"><a href="#index_mongoose-Schema">mongoose.Schema</a></h3><p>The Mongoose Schema constructor</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">mongoose.Schema = Schema;</code></pre></div><h4>Example:</h4>

<pre><code><span class="keyword">var</span> mongoose = require(<span class="string">'mongoose'</span>);
<span class="keyword">var</span> Schema = mongoose.Schema;
<span class="keyword">var</span> CatSchema = <span class="keyword">new</span> Schema(..);</code></pre><hr class=""></div><div class="item static public"><h3 id="index_mongoose-SchemaType"><a href="#index_mongoose-SchemaType">mongoose.SchemaType</a></h3><p>The Mongoose SchemaType constructor.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">mongoose.SchemaType = SchemaType;</code></pre></div><hr class=""></div><div class="item static public"><h3 id="index_mongoose-SchemaTypes"><a href="#index_mongoose-SchemaTypes">mongoose.SchemaTypes</a></h3><p>The various Mongoose SchemaTypes.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">mongoose.SchemaTypes = Schema.Types;</code></pre></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="#schema_Schema-Types" title="Schema.SchemaTypes">Schema.SchemaTypes</a></li></ul></div><h4>Note:</h4>

<p><em>Alias of mongoose.Schema.Types for backwards compatibility.</em></p><hr class=""></div><div class="item static public"><h3 id="index_mongoose-VirtualType"><a href="#index_mongoose-VirtualType">mongoose.VirtualType</a></h3><p>The Mongoose VirtualType constructor.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">mongoose.VirtualType = VirtualType;</code></pre></div><hr class=""></div><div class="item static public"><h3 id="index_mongoose-Types"><a href="#index_mongoose-Types">mongoose.Types</a></h3><p>The various Mongoose Types.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">mongoose.Types = Types;</code></pre></div><h4>Example:</h4>

<pre><code><span class="keyword">var</span> mongoose = require(<span class="string">'mongoose'</span>);
<span class="keyword">var</span> array = mongoose.Types.Array;</code></pre>

<h4>Types:</h4>

<ul>
<li>Array</li>
<li>Buffer</li>
<li>Document</li>
<li>Embedded</li>
<li>DocumentArray</li>
<li>ObjectId</li>
</ul>

<p>Using this exposed access to the <code>ObjectId</code> type, we can construct ids on demand.</p>

<pre><code><span class="keyword">var</span> ObjectId = mongoose.Types.ObjectId;
<span class="keyword">var</span> id1 = <span class="keyword">new</span> ObjectId;</code></pre><hr class=""></div><div class="item static public"><h3 id="index_mongoose-Query"><a href="#index_mongoose-Query">mongoose.Query</a></h3><p>The Mongoose Query constructor.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">mongoose.Query = Query;</code></pre></div><hr class=""></div><div class="item static public"><h3 id="index_mongoose-Promise"><a href="#index_mongoose-Promise">mongoose.Promise</a></h3><p>The Mongoose Promise constructor.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">mongoose.Promise = Promise;</code></pre></div><hr class=""></div><div class="item static public"><h3 id="index_mongoose-Model"><a href="#index_mongoose-Model">mongoose.Model</a></h3><p>The Mongoose Model constructor.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">mongoose.Model = Model;</code></pre></div><hr class=""></div><div class="item static public"><h3 id="index_mongoose-Document"><a href="#index_mongoose-Document">mongoose.Document</a></h3><p>The Mongoose Document constructor.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">mongoose.Document = Document;</code></pre></div><hr class=""></div><div class="item static public"><h3 id="index_mongoose-Error"><a href="#index_mongoose-Error">mongoose.Error</a></h3><p>The MongooseError constructor.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">mongoose.Error = require(<span class="string">'./error'</span>);</code></pre></div><hr class=""></div><div class="item static public"><h3 id="index_mongoose-mongo"><a href="#index_mongoose-mongo">mongoose.mongo</a></h3><p>The node-mongodb-native driver Mongoose uses.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">mongoose.mongo = require(<span class="string">'mongodb'</span>);</code></pre></div><hr class=""></div><div class="item property public"><h3 id="index_Mongoose-connection"><a href="#index_Mongoose-connection">Mongoose#<span>connection</span></a></h3><p>The default connection of the mongoose module.</p>

<h4>Example:</h4>

<pre><code><span class="keyword">var</span> mongoose = require(<span class="string">'mongoose'</span>);
mongoose.connect(...);
mongoose.connection.on(<span class="string">'error'</span>, cb);</code></pre>

<p>This is the connection used by default for every model created using <a href="#index_Mongoose-model">mongoose.model</a>.</p><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#connection_Connection">Connection</a>&gt; </span><span></span></li></ul></div><hr class=""></div></li><li class="module "><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/collection.js" id="collection-js">collection.js</a><div class="item method public"><h3 id="collection_Collection"><a href="#collection_Collection">Collection(<code>name</code>, <code>conn</code>, <code>opts</code>)</a></h3><p>Abstract Collection constructor</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">Collection</span> <span class="params">(name, conn, opts)</span> {</span>
  <span class="keyword">this</span>.name = name;
  <span class="keyword">this</span>.conn = conn;
  <span class="keyword">this</span>.buffer = <span class="literal">true</span>;
  <span class="keyword">this</span>.queue = [];

  <span class="keyword">if</span> (<span class="string">'number'</span> == <span class="keyword">typeof</span> opts) opts = { size: opts };
  <span class="keyword">this</span>.opts = opts || {};

  <span class="keyword">if</span> (STATES.connected == <span class="keyword">this</span>.conn.readyState) {
    <span class="keyword">this</span>.onOpen();
  }
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>name</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>name of the collection</span></li><li><code>conn</code><span class="types"> &lt;<a href="#connection_Connection">Connection</a>&gt; </span><span>A MongooseConnection instance</span></li><li><code>opts</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>optional collection options</span></li></ul></div><div class="description"><p>This is the base class that drivers inherit from and implement.</p></div><hr class=""></div><div class="item method private"><h3 id="collection_Collection-onOpen"><a href="#collection_Collection-onOpen">Collection#onOpen()</a></h3><p>Called when the database connects</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Collection.prototype.onOpen = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">var</span> self = <span class="keyword">this</span>;
  <span class="keyword">this</span>.buffer = <span class="literal">false</span>;
  self.doQueue();
};</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="collection_Collection-onClose"><a href="#collection_Collection-onClose">Collection#onClose()</a></h3><p>Called when the database disconnects</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Collection.prototype.onClose = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">this</span>.buffer = <span class="literal">true</span>;
};</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="collection_Collection-addQueue"><a href="#collection_Collection-addQueue">Collection#addQueue(<code>name</code>, <code>args</code>)</a></h3><p>Queues a method for later execution when its<br />database connection opens.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Collection.prototype.addQueue = <span class="function"><span class="keyword">function</span> <span class="params">(name, args)</span> {</span>
  <span class="keyword">this</span>.queue.push([name, args]);
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>name</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>name of the method to queue</span></li><li><code>args</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array">Array</a>&gt; </span><span>arguments to pass to the method when executed</span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="collection_Collection-doQueue"><a href="#collection_Collection-doQueue">Collection#doQueue()</a></h3><p>Executes all queued methods and clears the queue.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Collection.prototype.doQueue = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>, l = <span class="keyword">this</span>.queue.length; i &lt; l; i++){
    <span class="keyword">this</span>[<span class="keyword">this</span>.queue[i][<span class="number">0</span>]].apply(<span class="keyword">this</span>, <span class="keyword">this</span>.queue[i][<span class="number">1</span>]);
  }
  <span class="keyword">this</span>.queue = [];
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="collection_Collection-ensureIndex"><a href="#collection_Collection-ensureIndex">Collection#ensureIndex()</a></h3><p>Abstract method that drivers must implement.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Collection.prototype.ensureIndex = <span class="keyword">function</span>(){
  <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">'Collection#ensureIndex unimplemented by driver'</span>);
};</code></pre></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="collection_Collection-findAndModify"><a href="#collection_Collection-findAndModify">Collection#findAndModify()</a></h3><p>Abstract method that drivers must implement.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Collection.prototype.findAndModify = <span class="keyword">function</span>(){
  <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">'Collection#findAndModify unimplemented by driver'</span>);
};</code></pre></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="collection_Collection-findOne"><a href="#collection_Collection-findOne">Collection#findOne()</a></h3><p>Abstract method that drivers must implement.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Collection.prototype.findOne = <span class="keyword">function</span>(){
  <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">'Collection#findOne unimplemented by driver'</span>);
};</code></pre></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="collection_Collection-find"><a href="#collection_Collection-find">Collection#find()</a></h3><p>Abstract method that drivers must implement.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Collection.prototype.find = <span class="keyword">function</span>(){
  <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">'Collection#find unimplemented by driver'</span>);
};</code></pre></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="collection_Collection-insert"><a href="#collection_Collection-insert">Collection#insert()</a></h3><p>Abstract method that drivers must implement.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Collection.prototype.insert = <span class="keyword">function</span>(){
  <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">'Collection#insert unimplemented by driver'</span>);
};</code></pre></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="collection_Collection-save"><a href="#collection_Collection-save">Collection#save()</a></h3><p>Abstract method that drivers must implement.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Collection.prototype.save = <span class="keyword">function</span>(){
  <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">'Collection#save unimplemented by driver'</span>);
};</code></pre></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="collection_Collection-update"><a href="#collection_Collection-update">Collection#update()</a></h3><p>Abstract method that drivers must implement.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Collection.prototype.update = <span class="keyword">function</span>(){
  <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">'Collection#update unimplemented by driver'</span>);
};</code></pre></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="collection_Collection-getIndexes"><a href="#collection_Collection-getIndexes">Collection#getIndexes()</a></h3><p>Abstract method that drivers must implement.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Collection.prototype.getIndexes = <span class="keyword">function</span>(){
  <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">'Collection#getIndexes unimplemented by driver'</span>);
};</code></pre></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="collection_Collection-mapReduce"><a href="#collection_Collection-mapReduce">Collection#mapReduce()</a></h3><p>Abstract method that drivers must implement.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Collection.prototype.mapReduce = <span class="keyword">function</span>(){
  <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">'Collection#mapReduce unimplemented by driver'</span>);
};</code></pre></div><div class="description"></div><hr class=""></div><div class="item property public"><h3 id="collection_Collection-conn"><a href="#collection_Collection-conn">Collection#<span>conn</span></a></h3><p>The Connection instance</p><hr class=""></div><div class="item property public"><h3 id="collection_Collection-name"><a href="#collection_Collection-name">Collection#<span>name</span></a></h3><p>The collection name</p><hr class=""></div></li><li class="module "><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/connection.js" id="connection-js">connection.js</a><div class="item method public"><h3 id="connection_Connection"><a href="#connection_Connection">Connection(<code>base</code>)</a></h3><p>Connection constructor</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">Connection</span> <span class="params">(base)</span> {</span>
  <span class="keyword">this</span>.base = base;
  <span class="keyword">this</span>.collections = {};
  <span class="keyword">this</span>.models = {};
  <span class="keyword">this</span>.replica = <span class="literal">false</span>;
  <span class="keyword">this</span>.host = <span class="literal">null</span>;
  <span class="keyword">this</span>.port = <span class="literal">null</span>;
  <span class="keyword">this</span>.user = <span class="literal">null</span>;
  <span class="keyword">this</span>.pass = <span class="literal">null</span>;
  <span class="keyword">this</span>.name = <span class="literal">null</span>;
  <span class="keyword">this</span>.options = <span class="literal">null</span>;
  <span class="keyword">this</span>._readyState = STATES.disconnected;
  <span class="keyword">this</span>._closeCalled = <span class="literal">false</span>;
  <span class="keyword">this</span>._hasOpened = <span class="literal">false</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>base</code><span class="types"> &lt;<a href="#index_Mongoose">Mongoose</a>&gt; </span><span>a mongoose instance</span></li></ul></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="http://nodejs.org/api/events.html#events_class_events_eventemitter" title="NodeJS EventEmitter">NodeJS EventEmitter</a></li></ul></div><div class="events"><h4>Events:</h4><ul><li><p><code>connecting</code>: Emitted when <code>connection.{open,openSet}()</code> is executed on this connection.</p></li><li><p><code>connected</code>: Emitted when this connection successfully connects to the db. May be emitted <em>multiple</em> times in <code>reconnected</code> scenarios.</p></li><li><p><code>open</code>: Emitted after we <code>connected</code> and <code>onOpen</code> is executed on all of this connections models.</p></li><li><p><code>disconnecting</code>: Emitted when <code>connection.close()</code> was executed.</p></li><li><p><code>disconnected</code>: Emitted after getting disconnected from the db.</p></li><li><p><code>close</code>: Emitted after we <code>disconnected</code> and <code>onClose</code> executed on all of this connections models.</p></li><li><p><code>reconnected</code>: Emitted after we <code>connected</code> and subsequently <code>disconnected</code>, followed by successfully another successfull connection.</p></li><li><p><code>error</code>: Emitted when an error occurs on this connection.</p></li><li><p><code>fullsetup</code>: Emitted in a replica-set scenario, when all nodes specified in the connection string are connected.</p></li></ul></div><div class="description"><p>For practical reasons, a Connection equals a Db.</p></div><hr class=""></div><div class="item method public"><h3 id="connection_Connection-open"><a href="#connection_Connection-open">Connection#open(<code>connection_string</code>, <code>[database]</code>, <code>[port]</code>, <code>[options]</code>, <code>[callback]</code>)</a></h3><p>Opens the connection to MongoDB.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Connection.prototype.open = <span class="function"><span class="keyword">function</span> <span class="params">(host, database, port, options, callback)</span> {</span>
  <span class="keyword">var</span> self = <span class="keyword">this</span>
    , uri;

  <span class="keyword">if</span> (<span class="string">'string'</span> === <span class="keyword">typeof</span> database) {
    <span class="keyword">switch</span> (arguments.length) {
      <span class="keyword">case</span> <span class="number">2</span>:
        port = <span class="number">27017</span>;
      <span class="keyword">case</span> <span class="number">3</span>:
        <span class="keyword">switch</span> (<span class="keyword">typeof</span> port) {
          <span class="keyword">case</span> <span class="string">'function'</span>:
            callback = port, port = <span class="number">27017</span>;
            <span class="keyword">break</span>;
          <span class="keyword">case</span> <span class="string">'object'</span>:
            options = port, port = <span class="number">27017</span>;
            <span class="keyword">break</span>;
        }
        <span class="keyword">break</span>;
      <span class="keyword">case</span> <span class="number">4</span>:
        <span class="keyword">if</span> (<span class="string">'function'</span> === <span class="keyword">typeof</span> options)
          callback = options, options = {};
    }
  } <span class="keyword">else</span> {
    <span class="keyword">switch</span> (<span class="keyword">typeof</span> database) {
      <span class="keyword">case</span> <span class="string">'function'</span>:
        callback = database, database = <span class="literal">undefined</span>;
        <span class="keyword">break</span>;
      <span class="keyword">case</span> <span class="string">'object'</span>:
        options = database;
        database = <span class="literal">undefined</span>;
        callback = port;
        <span class="keyword">break</span>;
    }

    <span class="keyword">if</span> (!rgxProtocol.test(host)) {
      host = <span class="string">'mongodb://'</span> + host;
    }

    uri = url.parse(host);
    host = uri.hostname;
    port = uri.port || <span class="number">27017</span>;
    database = uri.pathname &amp;&amp; uri.pathname.replace(<span class="regexp">/\//g</span>, <span class="string">''</span>);
  }

  <span class="keyword">this</span>.options = <span class="keyword">this</span>.defaultOptions(options);

  <span class="comment">// make sure we can open</span>
  <span class="keyword">if</span> (STATES.disconnected !== <span class="keyword">this</span>.readyState) {
    <span class="keyword">var</span> err = <span class="keyword">new</span> Error(<span class="string">'Trying to open unclosed connection.'</span>);
    err.state = <span class="keyword">this</span>.readyState;
    <span class="keyword">this</span>.error(err, callback);
    <span class="keyword">return</span> <span class="keyword">this</span>;
  }

  <span class="keyword">if</span> (!host) {
    <span class="keyword">this</span>.error(<span class="keyword">new</span> Error(<span class="string">'Missing connection hostname.'</span>), callback);
    <span class="keyword">return</span> <span class="keyword">this</span>;
  }

  <span class="keyword">if</span> (!database) {
    <span class="keyword">this</span>.error(<span class="keyword">new</span> Error(<span class="string">'Missing connection database.'</span>), callback);
    <span class="keyword">return</span> <span class="keyword">this</span>;
  }

  <span class="comment">// handle authentication</span>
  <span class="keyword">if</span> (uri &amp;&amp; uri.auth) {
    <span class="keyword">var</span> auth = uri.auth.split(<span class="string">':'</span>);
    <span class="keyword">this</span>.user = auth[<span class="number">0</span>];
    <span class="keyword">this</span>.pass = auth[<span class="number">1</span>];

  <span class="comment">// Check hostname for user/pass</span>
  } <span class="keyword">else</span> <span class="keyword">if</span> (<span class="regexp">/@/</span>.test(host) &amp;&amp; <span class="regexp">/:/</span>.test(host.split(<span class="string">'@'</span>)[<span class="number">0</span>])) {
    host = host.split(<span class="string">'@'</span>);
    <span class="keyword">var</span> auth = host.shift().split(<span class="string">':'</span>);
    host = host.pop();
    <span class="keyword">this</span>.user = auth[<span class="number">0</span>];
    <span class="keyword">this</span>.pass = auth[<span class="number">1</span>];

  <span class="comment">// user/pass options</span>
  } <span class="keyword">else</span> <span class="keyword">if</span> (options &amp;&amp; options.user &amp;&amp; options.pass) {
    <span class="keyword">this</span>.user = options.user;
    <span class="keyword">this</span>.pass = options.pass;

  } <span class="keyword">else</span> {
    <span class="keyword">this</span>.user = <span class="keyword">this</span>.pass = <span class="literal">undefined</span>;
  }

  <span class="keyword">this</span>.name = database;
  <span class="keyword">this</span>.host = host;
  <span class="keyword">this</span>.port = port;

  <span class="keyword">this</span>._open(callback);
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>connection_string</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>mongodb://uri or the host to which you are connecting</span></li><li><code>[database]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>database name</span></li><li><code>[port]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span>database port</span></li><li><code>[options]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>options</span></li><li><code>[callback]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="https://github.com/mongodb/node-mongodb-native" title="node-mongodb-native">node-mongodb-native</a></li></ul></div><div class="description"><p><code>options</code> is a hash with the following possible properties:</p>

<pre><code>db      - passed to the connection db instance
server  - passed to the connection server instance(s)
replset - passed to the connection ReplSetServer instance
user    - username <span class="keyword">for</span> authentication
pass    - password <span class="keyword">for</span> authentication</code></pre>

<h4>Notes:</h4>

<p>Mongoose forces the db option <code>forceServerObjectId</code> false and cannot be overridden.<br />Mongoose defaults the server <code>auto_reconnect</code> options to true which can be overridden.<br />See the node-mongodb-native driver instance for options that it understands.</p></div><hr class=""></div><div class="item method public"><h3 id="connection_Connection-openSet"><a href="#connection_Connection-openSet">Connection#openSet(<code>uris</code>, <code>[database]</code>, <code>[options]</code>, <code>[callback]</code>)</a></h3><p>Connects to a replica set.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Connection.prototype.openSet = <span class="function"><span class="keyword">function</span> <span class="params">(uris, database, options, callback)</span> {</span>
  <span class="keyword">var</span> uris = uris.split(<span class="string">','</span>)
    , self = <span class="keyword">this</span>;

  <span class="keyword">switch</span> (arguments.length) {
    <span class="keyword">case</span> <span class="number">3</span>:
      <span class="keyword">this</span>.name = database;
      <span class="keyword">if</span> (<span class="string">'function'</span> === <span class="keyword">typeof</span> options) callback = options, options = {};
      <span class="keyword">break</span>;
    <span class="keyword">case</span> <span class="number">2</span>:
      <span class="keyword">switch</span> (<span class="keyword">typeof</span> database) {
        <span class="keyword">case</span> <span class="string">'string'</span>:
          <span class="keyword">this</span>.name = database;
        <span class="keyword">case</span> <span class="string">'function'</span>:
          callback = database, database = <span class="literal">null</span>;
          <span class="keyword">break</span>;
        <span class="keyword">case</span> <span class="string">'object'</span>:
          options = database, database = <span class="literal">null</span>;
          <span class="keyword">break</span>;
      }
  }

  <span class="keyword">this</span>.options = options = <span class="keyword">this</span>.defaultOptions(options);

  <span class="keyword">if</span> (uris.length &lt; <span class="number">2</span>) {
    <span class="keyword">this</span>.error(<span class="keyword">new</span> Error(<span class="string">'Please provide comma-separated URIs'</span>), callback);
    <span class="keyword">return</span> <span class="keyword">this</span>;
  }

  <span class="keyword">this</span>.replica = <span class="literal">true</span>;
  <span class="keyword">this</span>.host = [];
  <span class="keyword">this</span>.port = [];

  uris.forEach(<span class="function"><span class="keyword">function</span> <span class="params">(uri)</span> {</span>
    <span class="comment">// handle missing protocols</span>
    <span class="keyword">if</span> (!rgxProtocol.test(uri))
      uri = <span class="string">'mongodb://'</span> + uri;

    <span class="keyword">var</span> uri = url.parse(uri);

    self.host.push(uri.hostname);
    self.port.push(uri.port || <span class="number">27017</span>);

    <span class="keyword">if</span> (!self.name &amp;&amp; uri.pathname &amp;&amp; uri.pathname.replace(<span class="regexp">/\//g</span>, <span class="string">''</span>))
      self.name = uri.pathname.replace(<span class="regexp">/\//g</span>, <span class="string">''</span>);

    <span class="keyword">if</span> (!self.user &amp;&amp; uri.auth) {
      <span class="keyword">var</span> auth = uri.auth.split(<span class="string">':'</span>);
      self.user = auth[<span class="number">0</span>];
      self.pass = auth[<span class="number">1</span>];
    }
  });

  <span class="keyword">if</span> (!<span class="keyword">this</span>.name) {
    <span class="keyword">this</span>.error(<span class="keyword">new</span> Error(<span class="string">'No database name provided for replica set'</span>), callback);
    <span class="keyword">return</span> <span class="keyword">this</span>;
  }

  <span class="keyword">this</span>._open(callback);
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>uris</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>comma-separated mongodb:// `URI`s</span></li><li><code>[database]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>database name if not included in `uris`</span></li><li><code>[options]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>passed to the internal driver</span></li><li><code>[callback]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="https://github.com/mongodb/node-mongodb-native" title="node-mongodb-native">node-mongodb-native</a></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code><span class="keyword">var</span> db = mongoose.createConnection();
db.openSet(<span class="string">"mongodb://user:pwd@localhost:27020/testing,mongodb://example.com:27020,mongodb://localhost:27019"</span>);</code></pre>

<p>The database name and/or auth need only be included in one URI.<br />The <code>options</code> is a hash which is passed to the internal driver connection object.</p>

<p>Valid <code>options</code></p>

<pre><code>db      - passed to the connection db instance
server  - passed to the connection server instance(s)
replset - passed to the connection ReplSetServer instance
user    - username <span class="keyword">for</span> authentication
pass    - password <span class="keyword">for</span> authentication</code></pre></div><hr class=""></div><div class="item method private"><h3 id="connection_Connection-error"><a href="#connection_Connection-error">Connection#error(<code>err</code>, <code>callback</code>)</a></h3><p>error</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Connection.prototype.error = <span class="function"><span class="keyword">function</span> <span class="params">(err, callback)</span> {</span>
  <span class="keyword">if</span> (callback) <span class="keyword">return</span> callback(err);
  <span class="keyword">this</span>.emit(<span class="string">'error'</span>, err);
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>err</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error">Error</a>&gt; </span><span></span></li><li><code>callback</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span>optional</span></li></ul></div><div class="description"><p>Graceful error handling, passes error to callback<br />if available, else emits error on the connection.</p></div><hr class="private"></div><div class="item method private"><h3 id="connection_Connection-_open"><a href="#connection_Connection-_open">Connection#_open(<code>callback</code>)</a></h3><p>Handles opening the connection with the appropriate method based on connection type.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Connection.prototype._open = <span class="function"><span class="keyword">function</span> <span class="params">(callback)</span> {</span>
  <span class="keyword">this</span>.readyState = STATES.connecting;
  <span class="keyword">this</span>._closeCalled = <span class="literal">false</span>;

  <span class="keyword">var</span> self = <span class="keyword">this</span>;

  <span class="keyword">var</span> method = <span class="keyword">this</span>.replica
    ? <span class="string">'doOpenSet'</span>
    : <span class="string">'doOpen'</span>;

  <span class="comment">// open connection</span>
  <span class="keyword">this</span>[method](<span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
    <span class="keyword">if</span> (err) {
      self.readyState = STATES.disconnected;
      <span class="keyword">if</span> (self._hasOpened) {
        <span class="keyword">if</span> (callback) callback(err);
      } <span class="keyword">else</span> {
        self.error(err, callback);
      }
      <span class="keyword">return</span>;
    }

    self.onOpen();
    callback &amp;&amp; callback();
  });
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>callback</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="connection_Connection-onOpen"><a href="#connection_Connection-onOpen">Connection#onOpen()</a></h3><p>Called when the connection is opened</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Connection.prototype.onOpen = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">var</span> self = <span class="keyword">this</span>;

  <span class="function"><span class="keyword">function</span> <span class="title">open</span> <span class="params">()</span> {</span>
    self.readyState = STATES.connected;

    <span class="comment">// avoid having the collection subscribe to our event emitter</span>
    <span class="comment">// to prevent 0.3 warning</span>
    <span class="keyword">for</span> (<span class="keyword">var</span> i <span class="keyword">in</span> self.collections)
      self.collections[i].onOpen();

    self.emit(<span class="string">'open'</span>);
  };

  <span class="comment">// re-authenticate</span>
  <span class="keyword">if</span> (self.user &amp;&amp; self.pass)
    self.db.authenticate(self.user, self.pass, open);
  <span class="keyword">else</span>
    open();
};</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="connection_Connection-close"><a href="#connection_Connection-close">Connection#close(<code>[callback]</code>)</a></h3><p>Closes the connection</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Connection.prototype.close = <span class="function"><span class="keyword">function</span> <span class="params">(callback)</span> {</span>
  <span class="keyword">var</span> self = <span class="keyword">this</span>;
  <span class="keyword">this</span>._closeCalled = <span class="literal">true</span>;

  <span class="keyword">switch</span> (<span class="keyword">this</span>.readyState){
    <span class="keyword">case</span> <span class="number">0</span>: <span class="comment">// disconnected</span>
      callback &amp;&amp; callback();
      <span class="keyword">break</span>;

    <span class="keyword">case</span> <span class="number">1</span>: <span class="comment">// connected</span>
      <span class="keyword">this</span>.readyState = STATES.disconnecting;
      <span class="keyword">this</span>.doClose(<span class="keyword">function</span>(err){
        <span class="keyword">if</span> (err){
          self.error(err, callback);
        } <span class="keyword">else</span> {
          self.onClose();
          callback &amp;&amp; callback();
        }
      });
      <span class="keyword">break</span>;

    <span class="keyword">case</span> <span class="number">2</span>: <span class="comment">// connecting</span>
      <span class="keyword">this</span>.once(<span class="string">'open'</span>, <span class="keyword">function</span>(){
        self.close(callback);
      });
      <span class="keyword">break</span>;

    <span class="keyword">case</span> <span class="number">3</span>: <span class="comment">// disconnecting</span>
      <span class="keyword">if</span> (!callback) <span class="keyword">break</span>;
      <span class="keyword">this</span>.once(<span class="string">'close'</span>, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
        callback();
      });
      <span class="keyword">break</span>;
  }

  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>[callback]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span>optional</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#connection_Connection">Connection</a>&gt; </span><span>self</span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method private"><h3 id="connection_Connection-onClose"><a href="#connection_Connection-onClose">Connection#onClose()</a></h3><p>Called when the connection closes</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Connection.prototype.onClose = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">this</span>.readyState = STATES.disconnected;

  <span class="comment">// avoid having the collection subscribe to our event emitter</span>
  <span class="comment">// to prevent 0.3 warning</span>
  <span class="keyword">for</span> (<span class="keyword">var</span> i <span class="keyword">in</span> <span class="keyword">this</span>.collections)
    <span class="keyword">this</span>.collections[i].onClose();

  <span class="keyword">this</span>.emit(<span class="string">'close'</span>);
};</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="connection_Connection-collection"><a href="#connection_Connection-collection">Connection#collection(<code>name</code>, <code>[options]</code>)</a></h3><p>Retrieves a collection, creating it if not cached.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Connection.prototype.collection = <span class="function"><span class="keyword">function</span> <span class="params">(name, options)</span> {</span>
  <span class="keyword">if</span> (!(name <span class="keyword">in</span> <span class="keyword">this</span>.collections))
    <span class="keyword">this</span>.collections[name] = <span class="keyword">new</span> Collection(name, <span class="keyword">this</span>, options);
  <span class="keyword">return</span> <span class="keyword">this</span>.collections[name];
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>name</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>of the collection</span></li><li><code>[options]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>optional collection options</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#collection_Collection">Collection</a>&gt; </span><span>collection instance</span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="connection_Connection-model"><a href="#connection_Connection-model">Connection#model(<code>name</code>, <code>[schema]</code>, <code>[collection]</code>)</a></h3><p>Defines or retrieves a model.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Connection.prototype.model = <span class="function"><span class="keyword">function</span> <span class="params">(name, schema, collection)</span> {</span>
  <span class="keyword">if</span> (!<span class="keyword">this</span>.models[name]) {
    <span class="keyword">var</span> model = <span class="keyword">this</span>.base.model(name, schema, collection, <span class="literal">true</span>)
      , Model

    <span class="keyword">if</span> (<span class="keyword">this</span> != model.prototype.db) {
      <span class="comment">// subclass model using this connection and collection name</span>
      Model = <span class="function"><span class="keyword">function</span> <span class="title">Model</span> <span class="params">(doc, fields, skipId)</span> {</span>
        <span class="keyword">if</span> (!(<span class="keyword">this</span> <span class="keyword">instanceof</span> Model))
          <span class="keyword">return</span> <span class="keyword">new</span> Model(doc, fields, skipId);
        model.call(<span class="keyword">this</span>, doc, fields, skipId);
      };

      Model.__proto__ = model;
      Model.prototype.__proto__ = model.prototype;
      Model.db = Model.prototype.db = <span class="keyword">this</span>;

      <span class="comment">// collection name discovery</span>
      <span class="keyword">if</span> (<span class="string">'string'</span> === <span class="keyword">typeof</span> schema) {
        collection = schema;
      }

      <span class="keyword">if</span> (!collection) {
        collection = model.prototype.schema.set(<span class="string">'collection'</span>) || utils.toCollectionName(name);
      }

      <span class="keyword">var</span> s = <span class="string">'string'</span> != <span class="keyword">typeof</span> schema
        ? schema
        : model.prototype.schema;

      Model.prototype.collection = <span class="keyword">this</span>.collection(collection, s &amp;&amp; s.options.capped);
      Model.collection = Model.prototype.collection;
      Model.init();
    }

    <span class="keyword">this</span>.models[name] = Model || model;
  }

  <span class="keyword">return</span> <span class="keyword">this</span>.models[name];
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>name</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>the model name</span></li><li><code>[schema]</code><span class="types"> &lt;<a href="#schema_Schema">Schema</a>&gt; </span><span>a schema. necessary when defining a model</span></li><li><code>[collection]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>name of mongodb collection (optional) if not given it will be induced from model name</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#model_Model">Model</a>&gt; </span><span>The compiled model</span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="#index_Mongoose-model" title="Mongoose#model">Mongoose#model</a></li></ul></div><div class="description"><pre><code><span class="keyword">var</span> mongoose = require(<span class="string">'mongoose'</span>);
<span class="keyword">var</span> db = mongoose.createConnection(..);
db.model(<span class="string">'Venue'</span>, <span class="keyword">new</span> Schema(..));
<span class="keyword">var</span> Ticket = db.model(<span class="string">'Ticket'</span>, <span class="keyword">new</span> Schema(..));
<span class="keyword">var</span> Venue = db.model(<span class="string">'Venue'</span>);</code></pre></div><hr class=""></div><div class="item method public"><h3 id="connection_Connection-setProfiling"><a href="#connection_Connection-setProfiling">Connection#setProfiling(<code>level</code>, <code>[ms]</code>, <code>callback</code>)</a></h3><p>Set profiling level.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Connection.prototype.setProfiling = <span class="function"><span class="keyword">function</span> <span class="params">(level, ms, callback)</span> {</span>
  <span class="keyword">if</span> (STATES.connected !== <span class="keyword">this</span>.readyState) {
    <span class="keyword">return</span> <span class="keyword">this</span>.on(<span class="string">'open'</span>, <span class="keyword">this</span>.setProfiling.bind(<span class="keyword">this</span>, level, ms, callback));
  }

  <span class="keyword">if</span> (!callback) callback = ms, ms = <span class="number">100</span>;

  <span class="keyword">var</span> cmd = {};

  <span class="keyword">switch</span> (level) {
    <span class="keyword">case</span> <span class="number">0</span>:
    <span class="keyword">case</span> <span class="string">'off'</span>:
      cmd.profile = <span class="number">0</span>;
      <span class="keyword">break</span>;
    <span class="keyword">case</span> <span class="number">1</span>:
    <span class="keyword">case</span> <span class="string">'slow'</span>:
      cmd.profile = <span class="number">1</span>;
      <span class="keyword">if</span> (<span class="string">'number'</span> !== <span class="keyword">typeof</span> ms) {
        ms = parseInt(ms, <span class="number">10</span>);
        <span class="keyword">if</span> (isNaN(ms)) ms = <span class="number">100</span>;
      }
      cmd.slowms = ms;
      <span class="keyword">break</span>;
    <span class="keyword">case</span> <span class="number">2</span>:
    <span class="keyword">case</span> <span class="string">'all'</span>:
      cmd.profile = <span class="number">2</span>;
      <span class="keyword">break</span>;
    <span class="keyword">default</span>:
      <span class="keyword">return</span> callback(<span class="keyword">new</span> Error(<span class="string">'Invalid profiling level: '</span>+ level));
  }

  <span class="keyword">this</span>.db.executeDbCommand(cmd, <span class="function"><span class="keyword">function</span> <span class="params">(err, resp)</span> {</span>
    <span class="keyword">if</span> (err) <span class="keyword">return</span> callback(err);

    <span class="keyword">var</span> doc = resp.documents[<span class="number">0</span>];

    err = <span class="number">1</span> === doc.ok
      ? <span class="literal">null</span>
      : <span class="keyword">new</span> Error(<span class="string">'Could not set profiling level to: '</span>+ level)

    callback(err, doc);
  });
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>level</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>either off (0), slow (1), or all (2)</span></li><li><code>[ms]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span>the threshold in milliseconds above which queries will be logged when in `slow` mode. defaults to 100.</span></li><li><code>callback</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method private"><h3 id="connection_Connection-defaultOptions"><a href="#connection_Connection-defaultOptions">Connection#defaultOptions(<code>options</code>)</a></h3><p>Prepares default connection options.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Connection.prototype.defaultOptions = <span class="function"><span class="keyword">function</span> <span class="params">(options)</span> {</span>
  <span class="keyword">var</span> o = options || {};

  o.server = o.server || {};

  <span class="keyword">if</span> (!(<span class="string">'auto_reconnect'</span> <span class="keyword">in</span> o.server)) {
    o.server.auto_reconnect = <span class="literal">true</span>;
  }

  o.db = o.db || {};
  o.db.forceServerObjectId = <span class="literal">false</span>;

  <span class="keyword">return</span> o;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>options</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item property public"><h3 id="connection_Connection-db"><a href="#connection_Connection-db">Connection#<span>db</span></a></h3><p>The mongodb.Db instance, set when the connection is opened</p><hr class=""></div><div class="item property public"><h3 id="connection_Connection-collections"><a href="#connection_Connection-collections">Connection#<span>collections</span></a></h3><p>A hash of the collections associated with this connection</p><hr class=""></div><div class="item property public"><h3 id="connection_Connection-readyState"><a href="#connection_Connection-readyState">Connection#<span>readyState</span></a></h3><p>Connection ready state</p>

<ul>
<li>0 = disconnected</li>
<li>1 = connected</li>
<li>2 = connecting</li>
<li>3 = disconnecting</li>
</ul>

<p>Each state change emits its associated event name.</p>

<h4>Example</h4>

<pre><code>conn.on(<span class="string">'connected'</span>, callback);
conn.on(<span class="string">'disconnected'</span>, callback);</code></pre><hr class=""></div></li><li class="module "><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/document.js" id="document-js">document.js</a><div class="item method private"><h3 id="document_Document"><a href="#document_Document">Document(<code>obj</code>, <code>[fields]</code>, <code>[skipId]</code>)</a></h3><p>Document constructor.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">Document</span> <span class="params">(obj, fields, skipId)</span> {</span>
  <span class="comment">// node &lt;0.4.3 bug</span>
  <span class="keyword">if</span> (!<span class="keyword">this</span>._events) <span class="keyword">this</span>._events = {};
  <span class="keyword">this</span>.setMaxListeners(<span class="number">0</span>);

  <span class="keyword">if</span> (<span class="string">'boolean'</span> === <span class="keyword">typeof</span> fields) {
    <span class="keyword">this</span>._strictMode = fields;
    <span class="keyword">this</span>._selected = fields = <span class="literal">undefined</span>;
  } <span class="keyword">else</span> {
    <span class="keyword">this</span>._strictMode = <span class="keyword">this</span>.schema.options &amp;&amp; <span class="keyword">this</span>.schema.options.strict;
    <span class="keyword">this</span>._selected = fields;
  }

  <span class="keyword">this</span>.isNew = <span class="literal">true</span>;
  <span class="keyword">this</span>.errors = <span class="literal">undefined</span>;
  <span class="keyword">this</span>._shardval = <span class="literal">undefined</span>;
  <span class="keyword">this</span>._saveError = <span class="literal">undefined</span>;
  <span class="keyword">this</span>._validationError = <span class="literal">undefined</span>;
  <span class="keyword">this</span>._adhocPaths = <span class="literal">undefined</span>;
  <span class="keyword">this</span>._removing = <span class="literal">undefined</span>;
  <span class="keyword">this</span>._inserting = <span class="literal">undefined</span>;
  <span class="keyword">this</span>.__version = <span class="literal">undefined</span>;
  <span class="keyword">this</span>.__getters = {};
  <span class="keyword">this</span>.__id = <span class="literal">undefined</span>;

  <span class="keyword">this</span>._activePaths = <span class="keyword">new</span> ActiveRoster;

  <span class="keyword">var</span> required = <span class="keyword">this</span>.schema.requiredPaths();
  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; required.length; ++i) {
    <span class="keyword">this</span>._activePaths.require(required[i]);
  }

  <span class="keyword">this</span>._doc = <span class="keyword">this</span>._buildDoc(obj, fields, skipId);
  <span class="keyword">if</span> (obj) <span class="keyword">this</span>.set(obj, <span class="literal">undefined</span>, <span class="literal">true</span>);
  <span class="keyword">this</span>._registerHooks();
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>obj</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>the values to set</span></li><li><code>[fields]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>the fields which were selected in the query returning this document</span></li><li><code>[skipId]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span>bool, should we auto create an ObjectId _id</span></li></ul></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="http://nodejs.org/api/events.html#events_class_events_eventemitter" title="NodeJS EventEmitter">NodeJS EventEmitter</a></li></ul></div><div class="events"><h4>Events:</h4><ul><li><p><code>init</code>: Emitted on a document after it has was retreived from the db and fully hydrated by Mongoose.</p></li><li><p><code>save</code>: Emitted when the document is successfully saved</p></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="document_Document-_buildDoc"><a href="#document_Document-_buildDoc">Document#_buildDoc(<code>obj</code>, <code>[fields]</code>, <code>[skipId]</code>)</a></h3><p>Builds the default doc structure</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype._buildDoc = <span class="function"><span class="keyword">function</span> <span class="params">(obj, fields, skipId)</span> {</span>
  <span class="keyword">var</span> doc = {}
    , self = <span class="keyword">this</span>
    , exclude
    , keys
    , key
    , ki

  <span class="comment">// determine if this doc is a result of a query with</span>
  <span class="comment">// excluded fields</span>
  <span class="keyword">if</span> (fields &amp;&amp; <span class="string">'Object'</span> === fields.constructor.name) {
    keys = Object.keys(fields);
    ki = keys.length;

    <span class="keyword">while</span> (ki--) {
      <span class="keyword">if</span> (<span class="string">'_id'</span> !== keys[ki]) {
        exclude = <span class="number">0</span> === fields[keys[ki]];
        <span class="keyword">break</span>;
      }
    }
  }

  <span class="keyword">var</span> paths = Object.keys(<span class="keyword">this</span>.schema.paths)
    , plen = paths.length
    , ii = <span class="number">0</span>

  <span class="keyword">for</span> (; ii &lt; plen; ++ii) {
    <span class="keyword">var</span> p = paths[ii];

    <span class="keyword">if</span> (<span class="string">'_id'</span> == p) {
      <span class="keyword">if</span> (skipId) <span class="keyword">continue</span>;
      <span class="keyword">if</span> (obj &amp;&amp; <span class="string">'_id'</span> <span class="keyword">in</span> obj) <span class="keyword">continue</span>;
    }

    <span class="keyword">var</span> type = <span class="keyword">this</span>.schema.paths[p]
      , path = p.split(<span class="string">'.'</span>)
      , len = path.length
      , last = len-<span class="number">1</span>
      , doc_ = doc
      , i = <span class="number">0</span>

    <span class="keyword">for</span> (; i &lt; len; ++i) {
      <span class="keyword">var</span> piece = path[i]
        , def

      <span class="keyword">if</span> (i === last) {
        <span class="keyword">if</span> (fields) {
          <span class="keyword">if</span> (exclude) {
            <span class="comment">// apply defaults to all non-excluded fields</span>
            <span class="keyword">if</span> (p <span class="keyword">in</span> fields) <span class="keyword">continue</span>;

            def = type.getDefault(self, <span class="literal">true</span>);
            <span class="keyword">if</span> (<span class="string">'undefined'</span> !== <span class="keyword">typeof</span> def) {
              doc_[piece] = def;
              self._activePaths.<span class="keyword">default</span>(p);
            }

          } <span class="keyword">else</span> <span class="keyword">if</span> (p <span class="keyword">in</span> fields) {
            <span class="comment">// selected field</span>
            def = type.getDefault(self, <span class="literal">true</span>);
            <span class="keyword">if</span> (<span class="string">'undefined'</span> !== <span class="keyword">typeof</span> def) {
              doc_[piece] = def;
              self._activePaths.<span class="keyword">default</span>(p);
            }
          }
        } <span class="keyword">else</span> {
          def = type.getDefault(self, <span class="literal">true</span>);
          <span class="keyword">if</span> (<span class="string">'undefined'</span> !== <span class="keyword">typeof</span> def) {
            doc_[piece] = def;
            self._activePaths.<span class="keyword">default</span>(p);
          }
        }
      } <span class="keyword">else</span> {
        doc_ = doc_[piece] || (doc_[piece] = {});
      }
    }
  };

  <span class="keyword">return</span> doc;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>obj</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[fields]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[skipId]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="document_Document-init"><a href="#document_Document-init">Document#init(<code>doc</code>, <code>fn</code>)</a></h3><p>Initializes the document without setters or marking anything modified.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype.init = <span class="function"><span class="keyword">function</span> <span class="params">(doc, fn)</span> {</span>
  <span class="keyword">this</span>.isNew = <span class="literal">false</span>;

  init(<span class="keyword">this</span>, doc, <span class="keyword">this</span>._doc);
  <span class="keyword">this</span>._storeShard();

  <span class="keyword">this</span>.emit(<span class="string">'init'</span>);
  <span class="keyword">if</span> (fn) fn(<span class="literal">null</span>);
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>doc</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>document returned by mongo</span></li><li><code>fn</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span>callback</span></li></ul></div><div class="description"><p>Called internally after a document is returned from mongodb.</p></div><hr class="private"></div><div class="item method private"><h3 id="document_Document-_storeShard"><a href="#document_Document-_storeShard">Document#_storeShard()</a></h3><p>Stores the current values of the shard keys.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype._storeShard = <span class="function"><span class="keyword">function</span> <span class="title">_storeShard</span> <span class="params">()</span> {</span>
  <span class="comment">// backwards compat</span>
  <span class="keyword">var</span> key = <span class="keyword">this</span>.schema.options.shardKey || <span class="keyword">this</span>.schema.options.shardkey;
  <span class="keyword">if</span> (!(key &amp;&amp; <span class="string">'Object'</span> == key.constructor.name)) <span class="keyword">return</span>;

  <span class="keyword">var</span> orig = <span class="keyword">this</span>._shardval = {}
    , paths = Object.keys(key)
    , len = paths.length
    , val

  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; len; ++i) {
    val = <span class="keyword">this</span>.getValue(paths[i]);
    <span class="keyword">if</span> (isMongooseObject(val)) {
      orig[paths[i]] = val.toObject({ depopulate: <span class="literal">true</span> })
    } <span class="keyword">else</span> <span class="keyword">if</span> (<span class="literal">null</span> != val &amp;&amp; val.valueOf) {
      orig[paths[i]] = val.valueOf();
    } <span class="keyword">else</span> {
      orig[paths[i]] = val;
    }
  }
}</code></pre></div><div class="description"><h4>Note:</h4>

<p><em>Shard key values do not / are not allowed to change.</em></p></div><hr class="private"></div><div class="item method public"><h3 id="document_Document-update"><a href="#document_Document-update">Document#update(<code>doc</code>, <code>options</code>, <code>callback</code>)</a></h3><p>Sends an update command with this document <code>_id</code> as the query selector.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype.update = <span class="function"><span class="keyword">function</span> <span class="title">update</span> <span class="params">()</span> {</span>
  <span class="keyword">var</span> args = utils.args(arguments);
  args.unshift({_id: <span class="keyword">this</span>._id});
  <span class="keyword">this</span>.constructor.update.apply(<span class="keyword">this</span>.constructor, args);
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>doc</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>options</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>callback</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span></span></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code>weirdCar.update({$inc: {wheels:<span class="number">1</span>}}, { safe: <span class="literal">true</span> }, callback);</code></pre>

<h4>Valid options:</h4>

<ul>
<li><code>safe</code> safe mode (defaults to value set in schema (true))</li>
<li><code>upsert</code> (boolean) whether to create the doc if it doesn't match (false)</li>
</ul></div><hr class=""></div><div class="item method public"><h3 id="document_Document-set"><a href="#document_Document-set">Document#set(<code>path</code>, <code>val</code>, <code>[type]</code>)</a></h3><p>Sets the value of a path, or many paths.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype.set = <span class="function"><span class="keyword">function</span> <span class="params">(path, val, type)</span> {</span>
  <span class="keyword">var</span> constructing = <span class="literal">true</span> === type
    , adhoc = type &amp;&amp; <span class="literal">true</span> !== type
    , adhocs

  <span class="keyword">if</span> (adhoc) {
    adhocs = <span class="keyword">this</span>._adhocPaths || (<span class="keyword">this</span>._adhocPaths = {});
    adhocs[path] = Schema.interpretAsType(path, type);
  }

  <span class="keyword">if</span> (<span class="string">'string'</span> !== <span class="keyword">typeof</span> path) {
    <span class="comment">// new Document({ key: val })</span>

    <span class="keyword">if</span> (<span class="literal">null</span> === path || <span class="literal">undefined</span> === path) {
      <span class="keyword">var</span> _ = path;
      path = val;
      val = _;

    } <span class="keyword">else</span> {
      <span class="keyword">var</span> prefix = val
        ? val + <span class="string">'.'</span>
        : <span class="string">''</span>;

      <span class="keyword">if</span> (path <span class="keyword">instanceof</span> Document) path = path._doc;

      <span class="keyword">var</span> keys = Object.keys(path)
        , i = keys.length
        , pathtype
        , key

      <span class="keyword">while</span> (i--) {
        key = keys[i];
        <span class="keyword">if</span> (<span class="literal">null</span> != path[key] &amp;&amp; <span class="string">'Object'</span> === path[key].constructor.name
          &amp;&amp; !(<span class="keyword">this</span>._path(prefix + key) <span class="keyword">instanceof</span> MixedSchema)) {
          <span class="keyword">this</span>.set(path[key], prefix + key, constructing);
        } <span class="keyword">else</span> <span class="keyword">if</span> (<span class="keyword">this</span>._strictMode) {
          pathtype = <span class="keyword">this</span>.schema.pathType(prefix + key);
          <span class="keyword">if</span> (<span class="string">'real'</span> === pathtype || <span class="string">'virtual'</span> === pathtype) {
            <span class="keyword">this</span>.set(prefix + key, path[key], constructing);
          } <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">'throw'</span> == <span class="keyword">this</span>._strictMode) {
            <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">"Field `"</span> + key + <span class="string">"` is not in schema."</span>);
          }
        } <span class="keyword">else</span> <span class="keyword">if</span> (<span class="literal">undefined</span> !== path[key]) {
          <span class="keyword">this</span>.set(prefix + key, path[key], constructing);
        }
      }

      <span class="keyword">return</span> <span class="keyword">this</span>;
    }
  }

  <span class="comment">// ensure _strict is honored for obj props</span>
  <span class="comment">// docschema = new Schema({ path: { nest: 'string' }})</span>
  <span class="comment">// doc.set('path', obj);</span>
  <span class="keyword">var</span> pathType = <span class="keyword">this</span>.schema.pathType(path);
  <span class="keyword">if</span> (<span class="string">'nested'</span> == pathType &amp;&amp; val &amp;&amp; <span class="string">'Object'</span> == val.constructor.name) {
    <span class="keyword">this</span>.setValue(path, <span class="literal">null</span>);
    <span class="keyword">this</span>.set(val, path, constructing);
    <span class="keyword">return</span> <span class="keyword">this</span>;
  }

  <span class="keyword">var</span> schema;
  <span class="keyword">if</span> (<span class="string">'adhocOrUndefined'</span> == pathType &amp;&amp; <span class="keyword">this</span>._strictMode) {
    <span class="keyword">return</span> <span class="keyword">this</span>;
  } <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">'virtual'</span> == pathType) {
    schema = <span class="keyword">this</span>.schema.virtualpath(path);
    schema.applySetters(val, <span class="keyword">this</span>);
    <span class="keyword">return</span> <span class="keyword">this</span>;
  } <span class="keyword">else</span> {
    schema = <span class="keyword">this</span>._path(path);
  }

  <span class="keyword">var</span> parts = path.split(<span class="string">'.'</span>)
    , pathToMark

  <span class="comment">// When using the $set operator the path to the field must already exist.</span>
  <span class="comment">// Else mongodb throws: "LEFT_SUBFIELD only supports Object"</span>

  <span class="keyword">if</span> (parts.length &lt;= <span class="number">1</span>) {
    pathToMark = path;
  } <span class="keyword">else</span> {
    <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; parts.length; ++i) {
      <span class="keyword">var</span> part = parts[i];
      <span class="keyword">var</span> subpath = parts.slice(<span class="number">0</span>, i).concat(part).join(<span class="string">'.'</span>);
      <span class="keyword">if</span> (<span class="keyword">this</span>.isDirectModified(subpath) <span class="comment">// earlier prefixes that are already</span>
                                         <span class="comment">// marked as dirty have precedence</span>
          || <span class="keyword">this</span>.get(subpath) === <span class="literal">null</span>) {
        pathToMark = subpath;
        <span class="keyword">break</span>;
      }
    }

    <span class="keyword">if</span> (!pathToMark) pathToMark = path;
  }

  <span class="keyword">if</span> (!schema || <span class="literal">null</span> === val || <span class="literal">undefined</span> === val) {
    <span class="keyword">this</span>._set(pathToMark, path, constructing, parts, schema, val);
    <span class="keyword">return</span> <span class="keyword">this</span>;
  }

  <span class="keyword">var</span> self = <span class="keyword">this</span>;

  <span class="comment">// if this doc is being constructed we should not</span>
  <span class="comment">// trigger getters.</span>
  <span class="keyword">var</span> priorVal = constructing
    ? <span class="literal">undefined</span>
    : <span class="keyword">this</span>.get(path);

  <span class="keyword">var</span> shouldSet = <span class="keyword">this</span>.<span class="keyword">try</span>(<span class="keyword">function</span>(){
    val = schema.applySetters(val, self, <span class="literal">false</span>, priorVal);
  });

  <span class="keyword">if</span> (shouldSet) {
    <span class="keyword">this</span>._set(pathToMark, path, constructing, parts, schema, val, priorVal);
  }

  <span class="keyword">return</span> <span class="keyword">this</span>;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>path or object of key/vals to set</span></li><li><code>val</code><span class="types"> &lt;<a href="#Any">Any</a>&gt; </span><span>the value to set</span></li><li><code>[type]</code><span class="types"> &lt;<a href="#schema_Schema">Schema</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>, <a href="http://nodejs.org/api/buffer.html">Buffer</a>, <a href="#etc..">etc..</a>&gt; </span><span>optionally specify a type for &quot;on-the-fly&quot; attributes</span></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code><span class="comment">// path, value</span>
doc.set(path, value)

<span class="comment">// object</span>
doc.set({
    path  : value
  , path2 : {
       path  : value
    }
})

<span class="comment">// only-the-fly cast to number</span>
doc.set(path, value, Number)

<span class="comment">// only-the-fly cast to string</span>
doc.set(path, value, String)</code></pre></div><hr class=""></div><div class="item method private"><h3 id="document_Document-_set"><a href="#document_Document-_set">Document#_set()</a></h3><p>Handles the actual setting of the value and marking the path modified if appropriate.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype._set = <span class="function"><span class="keyword">function</span> <span class="params">(pathToMark, path, constructing, parts, schema, val, priorVal)</span> {</span>
  <span class="keyword">if</span> (<span class="keyword">this</span>.isNew) {
    <span class="keyword">this</span>.markModified(pathToMark);
  } <span class="keyword">else</span> {

    priorVal || (priorVal = <span class="keyword">this</span>.get(path));

    <span class="keyword">if</span> (!<span class="keyword">this</span>.isDirectModified(pathToMark)) {
      <span class="keyword">if</span> (<span class="literal">undefined</span> === val &amp;&amp; !<span class="keyword">this</span>.isSelected(path)) {
        <span class="comment">// special case:</span>
        <span class="comment">// when a path is not selected in a query its initial</span>
        <span class="comment">// value will be undefined.</span>
        <span class="keyword">this</span>.markModified(pathToMark, priorVal);
      } <span class="keyword">else</span> <span class="keyword">if</span> (<span class="literal">undefined</span> === val &amp;&amp; path <span class="keyword">in</span> <span class="keyword">this</span>._activePaths.states.<span class="keyword">default</span>) {
        <span class="comment">// do nothing</span>
        <span class="comment">// unsetting the default value which was never saved</span>
      } <span class="keyword">else</span> <span class="keyword">if</span> (!deepEqual(val, priorVal)) {
        <span class="keyword">this</span>.markModified(pathToMark, priorVal);
      } <span class="keyword">else</span> <span class="keyword">if</span> (!constructing &amp;&amp;
                 <span class="literal">null</span> != val &amp;&amp;
                 path <span class="keyword">in</span> <span class="keyword">this</span>._activePaths.states.<span class="keyword">default</span> &amp;&amp;
                 deepEqual(val, schema.getDefault(<span class="keyword">this</span>, constructing))) {
        <span class="comment">// special case:</span>
        <span class="comment">// a path with a default was $unset on the server</span>
        <span class="comment">// and the user is setting it to the same value again</span>
        <span class="keyword">this</span>.markModified(pathToMark, priorVal);
      }
    }
  }

  <span class="keyword">var</span> obj = <span class="keyword">this</span>._doc
    , i = <span class="number">0</span>
    , l = parts.length

  <span class="keyword">for</span> (; i &lt; l; i++) {
    <span class="keyword">var</span> next = i + <span class="number">1</span>
      , last = next === l;

    <span class="keyword">if</span> (last) {
      obj[parts[i]] = val;
    } <span class="keyword">else</span> {
      <span class="keyword">if</span> (obj[parts[i]] &amp;&amp; <span class="string">'Object'</span> === obj[parts[i]].constructor.name) {
        obj = obj[parts[i]];
      } <span class="keyword">else</span> <span class="keyword">if</span> (obj[parts[i]] &amp;&amp; Array.isArray(obj[parts[i]])) {
        obj = obj[parts[i]];
      } <span class="keyword">else</span> {
        obj = obj[parts[i]] = {};
      }
    }
  }
};</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="document_Document-getValue"><a href="#document_Document-getValue">Document#getValue(<code>path</code>)</a></h3><p>Gets a raw value from a path (no getters)</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype.getValue = <span class="function"><span class="keyword">function</span> <span class="params">(path)</span> {</span>
  <span class="keyword">var</span> parts = path.split(<span class="string">'.'</span>)
    , obj = <span class="keyword">this</span>._doc
    , part;

  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>, l = parts.length; i &lt; l; i++) {
    part = parts[i];
    obj = obj.getValue
        ? obj.getValue(part) <span class="comment">// If we have an embedded array document member</span>
        : obj[part];
    <span class="keyword">if</span> (!obj) <span class="keyword">return</span> obj;
  }

  <span class="keyword">return</span> obj;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="document_Document-setValue"><a href="#document_Document-setValue">Document#setValue(<code>path</code>, <code>value</code>)</a></h3><p>Sets a raw value for a path (no casting, setters, transformations)</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype.setValue = <span class="function"><span class="keyword">function</span> <span class="params">(path, val)</span> {</span>
  <span class="keyword">var</span> parts = path.split(<span class="string">'.'</span>)
    , obj = <span class="keyword">this</span>._doc;

  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>, len = parts.length-<span class="number">1</span>; i &lt; len; i++) {
    obj = obj[parts[i]];
  }

  obj[parts[len]] = val;
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>value</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="document_Document-get"><a href="#document_Document-get">Document#get(<code>path</code>, <code>[type]</code>)</a></h3><p>Returns the value of a path.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype.get = <span class="function"><span class="keyword">function</span> <span class="params">(path, type)</span> {</span>
  <span class="keyword">var</span> adhocs;
  <span class="keyword">if</span> (type) {
    adhocs = <span class="keyword">this</span>._adhocPaths || (<span class="keyword">this</span>._adhocPaths = {});
    adhocs[path] = Schema.interpretAsType(path, type);
  }

  <span class="keyword">var</span> schema = <span class="keyword">this</span>._path(path) || <span class="keyword">this</span>.schema.virtualpath(path)
    , pieces = path.split(<span class="string">'.'</span>)
    , obj = <span class="keyword">this</span>._doc;

  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>, l = pieces.length; i &lt; l; i++) {
    obj = <span class="literal">null</span> == obj ? <span class="literal">null</span> : obj[pieces[i]];
  }

  <span class="keyword">if</span> (schema) {
    obj = schema.applyGetters(obj, <span class="keyword">this</span>);
  }

  <span class="keyword">return</span> obj;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>[type]</code><span class="types"> &lt;<a href="#schema_Schema">Schema</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>, <a href="http://nodejs.org/api/buffer.html">Buffer</a>, <a href="#etc..">etc..</a>&gt; </span><span>optionally specify a type for on-the-fly attributes</span></li></ul></div><div class="description"><h4>Example</h4>

<pre><code><span class="comment">// path</span>
doc.get(<span class="string">'age'</span>) <span class="comment">// 47</span>

<span class="comment">// dynamic casting to a string</span>
doc.get(<span class="string">'age'</span>, String) <span class="comment">// "47"</span></code></pre></div><hr class=""></div><div class="item method private"><h3 id="document_Document-_path"><a href="#document_Document-_path">Document#_path(<code>path</code>)</a></h3><p>Returns the schematype for the given <code>path</code>.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype._path = <span class="function"><span class="keyword">function</span> <span class="params">(path)</span> {</span>
  <span class="keyword">var</span> adhocs = <span class="keyword">this</span>._adhocPaths
    , adhocType = adhocs &amp;&amp; adhocs[path];

  <span class="keyword">if</span> (adhocType) {
    <span class="keyword">return</span> adhocType;
  } <span class="keyword">else</span> {
    <span class="keyword">return</span> <span class="keyword">this</span>.schema.path(path);
  }
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="document_Document-markModified"><a href="#document_Document-markModified">Document#markModified(<code>path</code>)</a></h3><p>Marks the path as having pending changes to write to the db.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype.markModified = <span class="function"><span class="keyword">function</span> <span class="params">(path)</span> {</span>
  <span class="keyword">this</span>._activePaths.modify(path);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>the path to mark modified</span></li></ul></div><div class="description"><p><em>Very helpful when using <a href="./schematypes.html#mixed">Mixed</a> types.</em></p>

<h4>Example:</h4>

<pre><code>doc.mixed.type = <span class="string">'changed'</span>;
doc.markModified(<span class="string">'mixed.type'</span>);
doc.save() <span class="comment">// changes to mixed.type are now persisted</span></code></pre></div><hr class=""></div><div class="item method private"><h3 id="document_Document-try"><a href="#document_Document-try">Document#try(<code>fn</code>, <code>scope</code>)</a></h3><p>Catches errors that occur during execution of <code>fn</code> and stores them to later be passed when <code>save()</code> is executed.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype.<span class="keyword">try</span> = <span class="function"><span class="keyword">function</span> <span class="params">(fn, scope)</span> {</span>
  <span class="keyword">var</span> res;
  <span class="keyword">try</span> {
    fn.call(scope);
    res = <span class="literal">true</span>;
  } <span class="keyword">catch</span> (e) {
    <span class="keyword">this</span>._error(e);
    res = <span class="literal">false</span>;
  }
  <span class="keyword">return</span> res;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>fn</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span>function to execute</span></li><li><code>scope</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>the scope with which to call fn</span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="document_Document-modifiedPaths"><a href="#document_Document-modifiedPaths">Document#modifiedPaths()</a></h3><p>Returns the list of paths that have been modified.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype.modifiedPaths = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">var</span> directModifiedPaths = Object.keys(<span class="keyword">this</span>._activePaths.states.modify);

  <span class="keyword">return</span> directModifiedPaths.reduce(<span class="function"><span class="keyword">function</span> <span class="params">(list, path)</span> {</span>
    <span class="keyword">var</span> parts = path.split(<span class="string">'.'</span>);
    <span class="keyword">return</span> list.concat(parts.reduce(<span class="function"><span class="keyword">function</span> <span class="params">(chains, part, i)</span> {</span>
      <span class="keyword">return</span> chains.concat(parts.slice(<span class="number">0</span>, i).concat(part).join(<span class="string">'.'</span>));
    }, []));
  }, []);
};</code></pre></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array">Array</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="document_Document-isModified"><a href="#document_Document-isModified">Document#isModified(<code>[path]</code>)</a></h3><p>Returns true if this document was modified, else false.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype.isModified = <span class="function"><span class="keyword">function</span> <span class="params">(path)</span> {</span>
  <span class="keyword">return</span> path
    ? !!~<span class="keyword">this</span>.modifiedPaths().indexOf(path)
    : <span class="keyword">this</span>._activePaths.some(<span class="string">'modify'</span>);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>[path]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>optional</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span></span></li></ul></div><div class="description"><p>If <code>path</code> is given, checks if a path or any full path containing <code>path</code> as part of its path chain has been modified.</p>

<h4>Example</h4>

<pre><code>doc.set(<span class="string">'documents.0.title'</span>, <span class="string">'changed'</span>);
doc.isModified()                    <span class="comment">// true</span>
doc.isModified(<span class="string">'documents'</span>)         <span class="comment">// true</span>
doc.isModified(<span class="string">'documents.0.title'</span>) <span class="comment">// true</span>
doc.isDirectModified(<span class="string">'documents'</span>)   <span class="comment">// false</span></code></pre></div><hr class=""></div><div class="item method public"><h3 id="document_Document-isDirectModified"><a href="#document_Document-isDirectModified">Document#isDirectModified(<code>path</code>)</a></h3><p>Returns true if <code>path</code> was directly set and modified, else false.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype.isDirectModified = <span class="function"><span class="keyword">function</span> <span class="params">(path)</span> {</span>
  <span class="keyword">return</span> (path <span class="keyword">in</span> <span class="keyword">this</span>._activePaths.states.modify);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span></span></li></ul></div><div class="description"><h4>Example</h4>

<pre><code>doc.set(<span class="string">'documents.0.title'</span>, <span class="string">'changed'</span>);
doc.isDirectModified(<span class="string">'documents.0.title'</span>) <span class="comment">// true</span>
doc.isDirectModified(<span class="string">'documents'</span>) <span class="comment">// false</span></code></pre></div><hr class=""></div><div class="item method public"><h3 id="document_Document-isInit"><a href="#document_Document-isInit">Document#isInit(<code>path</code>)</a></h3><p>Checks if <code>path</code> was initialized.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype.isInit = <span class="function"><span class="keyword">function</span> <span class="params">(path)</span> {</span>
  <span class="keyword">return</span> (path <span class="keyword">in</span> <span class="keyword">this</span>._activePaths.states.init);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="document_Document-isSelected"><a href="#document_Document-isSelected">Document#isSelected(<code>path</code>)</a></h3><p>Checks if <code>path</code> was selected in the source query which initialized this document.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype.isSelected = <span class="function"><span class="keyword">function</span> <span class="title">isSelected</span> <span class="params">(path)</span> {</span>
  <span class="keyword">if</span> (<span class="keyword">this</span>._selected) {

    <span class="keyword">if</span> (<span class="string">'_id'</span> === path) {
      <span class="keyword">return</span> <span class="number">0</span> !== <span class="keyword">this</span>._selected._id;
    }

    <span class="keyword">var</span> paths = Object.keys(<span class="keyword">this</span>._selected)
      , i = paths.length
      , inclusive = <span class="literal">false</span>
      , cur

    <span class="keyword">if</span> (<span class="number">1</span> === i &amp;&amp; <span class="string">'_id'</span> === paths[<span class="number">0</span>]) {
      <span class="comment">// only _id was selected.</span>
      <span class="keyword">return</span> <span class="number">0</span> === <span class="keyword">this</span>._selected._id;
    }

    <span class="keyword">while</span> (i--) {
      cur = paths[i];
      <span class="keyword">if</span> (<span class="string">'_id'</span> == cur) <span class="keyword">continue</span>;
      inclusive = !! <span class="keyword">this</span>._selected[cur];
      <span class="keyword">break</span>;
    }

    <span class="keyword">if</span> (path <span class="keyword">in</span> <span class="keyword">this</span>._selected) {
      <span class="keyword">return</span> inclusive;
    }

    i = paths.length;
    <span class="keyword">var</span> pathDot = path + <span class="string">'.'</span>;

    <span class="keyword">while</span> (i--) {
      cur = paths[i];
      <span class="keyword">if</span> (<span class="string">'_id'</span> == cur) <span class="keyword">continue</span>;

      <span class="keyword">if</span> (<span class="number">0</span> === cur.indexOf(pathDot)) {
        <span class="keyword">return</span> inclusive;
      }

      <span class="keyword">if</span> (<span class="number">0</span> === pathDot.indexOf(cur)) {
        <span class="keyword">return</span> inclusive;
      }
    }

    <span class="keyword">return</span> ! inclusive;
  }

  <span class="keyword">return</span> <span class="literal">true</span>;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span></span></li></ul></div><div class="description"><h4>Example</h4>

<pre><code>Thing.findOne().select(<span class="string">'name'</span>).exec(<span class="function"><span class="keyword">function</span> <span class="params">(err, doc)</span> {</span>
   doc.isSelected(<span class="string">'name'</span>) <span class="comment">// true</span>
   doc.isSelected(<span class="string">'age'</span>)  <span class="comment">// false</span>
})</code></pre></div><hr class=""></div><div class="item method public"><h3 id="document_Document-validate"><a href="#document_Document-validate">Document#validate(<code>cb</code>)</a></h3><p>Executes registered validation rules for this document.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype.validate = <span class="function"><span class="keyword">function</span> <span class="params">(cb)</span> {</span>
  <span class="keyword">var</span> self = <span class="keyword">this</span>

  <span class="comment">// only validate required fields when necessary</span>
  <span class="keyword">var</span> paths = Object.keys(<span class="keyword">this</span>._activePaths.states.require).filter(<span class="function"><span class="keyword">function</span> <span class="params">(path)</span> {</span>
    <span class="keyword">if</span> (!self.isSelected(path) &amp;&amp; !self.isModified(path)) <span class="keyword">return</span> <span class="literal">false</span>;
    <span class="keyword">return</span> <span class="literal">true</span>;
  });

  paths = paths.concat(Object.keys(<span class="keyword">this</span>._activePaths.states.init));
  paths = paths.concat(Object.keys(<span class="keyword">this</span>._activePaths.states.modify));

  <span class="keyword">if</span> (<span class="number">0</span> === paths.length) {
    complete();
    <span class="keyword">return</span> <span class="keyword">this</span>;
  }

  <span class="keyword">var</span> validating = {}
    , total = <span class="number">0</span>;

  paths.forEach(validatePath);
  <span class="keyword">return</span> <span class="keyword">this</span>;

  <span class="function"><span class="keyword">function</span> <span class="title">validatePath</span> <span class="params">(path)</span> {</span>
    <span class="keyword">if</span> (validating[path]) <span class="keyword">return</span>;

    validating[path] = <span class="literal">true</span>;
    total++;

    process.nextTick(<span class="keyword">function</span>(){
      <span class="keyword">var</span> p = self.schema.path(path);
      <span class="keyword">if</span> (!p) <span class="keyword">return</span> --total || complete();

      p.doValidate(self.getValue(path), <span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
        <span class="keyword">if</span> (err) self.invalidate(path, err, <span class="literal">true</span>);
        --total || complete();
      }, self);
    });
  }

  <span class="function"><span class="keyword">function</span> <span class="title">complete</span> <span class="params">()</span> {</span>
    <span class="keyword">var</span> err = self._validationError;
    self._validationError = <span class="literal">undefined</span>;
    cb(err);
  }
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>cb</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span>called after validation completes, passing an error if one occurred</span></li></ul></div><div class="description"><h4>Note:</h4>

<p>This method is called <code>pre</code> save and if a validation rule is violated, <a href="#model_Model-save">save</a> is aborted and the error is returned to your <code>callback</code>.</p>

<h4>Example:</h4>

<pre><code>doc.validate(<span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
  <span class="keyword">if</span> (err) handleError(err);
  <span class="keyword">else</span> <span class="comment">// validation passed</span>
});</code></pre></div><hr class=""></div><div class="item method public"><h3 id="document_Document-invalidate"><a href="#document_Document-invalidate">Document#invalidate(<code>path</code>, <code>err</code>)</a></h3><p>Marks a path as invalid, causing validation to fail.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype.invalidate = <span class="function"><span class="keyword">function</span> <span class="params">(path, err)</span> {</span>
  <span class="keyword">if</span> (!<span class="keyword">this</span>._validationError) {
    <span class="keyword">this</span>._validationError = <span class="keyword">new</span> ValidationError(<span class="keyword">this</span>);
  }

  <span class="keyword">if</span> (!err || <span class="string">'string'</span> === <span class="keyword">typeof</span> err) {
    err = <span class="keyword">new</span> ValidatorError(path, err);
  }

  <span class="keyword">this</span>._validationError.errors[path] = err;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>the field to invalidate</span></li><li><code>err</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error">Error</a>&gt; </span><span>the error which states the reason `path` was invalid</span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method private"><h3 id="document_Document-_reset"><a href="#document_Document-_reset">Document#_reset()</a></h3><p>Resets the internal modified state of this document.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype._reset = <span class="function"><span class="keyword">function</span> <span class="title">reset</span> <span class="params">()</span> {</span>
  <span class="keyword">var</span> self = <span class="keyword">this</span>;
  DocumentArray || (DocumentArray = require(<span class="string">'./types/documentarray'</span>));

  <span class="keyword">this</span>._activePaths
  .map(<span class="string">'init'</span>, <span class="string">'modify'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(i)</span> {</span>
    <span class="keyword">return</span> self.getValue(i);
  })
  .filter(<span class="function"><span class="keyword">function</span> <span class="params">(val)</span> {</span>
    <span class="keyword">return</span> (val &amp;&amp; val <span class="keyword">instanceof</span> DocumentArray &amp;&amp; val.length);
  })
  .forEach(<span class="function"><span class="keyword">function</span> <span class="params">(array)</span> {</span>
    array.forEach(<span class="function"><span class="keyword">function</span> <span class="params">(doc)</span> {</span>
      doc._reset();
    });
  });

  <span class="comment">// clear atomics</span>
  <span class="keyword">this</span>._dirty().forEach(<span class="function"><span class="keyword">function</span> <span class="params">(dirt)</span> {</span>
    <span class="keyword">var</span> type = dirt.value;
    <span class="keyword">if</span> (type &amp;&amp; type._atomics) {
      type._atomics = {};
    }
  });

  <span class="comment">// Clear 'modify'('dirty') cache</span>
  <span class="keyword">this</span>._activePaths.clear(<span class="string">'modify'</span>);
  <span class="keyword">this</span>._validationError = <span class="literal">undefined</span>;
  <span class="keyword">this</span>.errors = <span class="literal">undefined</span>;
  <span class="keyword">var</span> self = <span class="keyword">this</span>;
  <span class="keyword">this</span>.schema.requiredPaths().forEach(<span class="function"><span class="keyword">function</span> <span class="params">(path)</span> {</span>
    self._activePaths.require(path);
  });

  <span class="keyword">return</span> <span class="keyword">this</span>;
}</code></pre></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#document_Document">Document</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="document_Document-_dirty"><a href="#document_Document-_dirty">Document#_dirty()</a></h3><p>Returns this documents dirty paths / vals.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype._dirty = <span class="function"><span class="keyword">function</span> <span class="title">_dirty</span> <span class="params">()</span> {</span>
  <span class="keyword">var</span> self = <span class="keyword">this</span>;

  <span class="keyword">var</span> all = <span class="keyword">this</span>._activePaths.map(<span class="string">'modify'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(path)</span> {</span>
    <span class="keyword">return</span> { path: path
           , value: self.getValue(path)
           , schema: self._path(path) };
  });

  <span class="comment">// Sort dirty paths in a flat hierarchy.</span>
  all.sort(<span class="function"><span class="keyword">function</span> <span class="params">(a, b)</span> {</span>
    <span class="keyword">return</span> (a.path &lt; b.path ? -<span class="number">1</span> : (a.path > b.path ? <span class="number">1</span> : <span class="number">0</span>));
  });

  <span class="comment">// Ignore "foo.a" if "foo" is dirty already.</span>
  <span class="keyword">var</span> minimal = []
    , lastPath
    , top;

  all.forEach(<span class="function"><span class="keyword">function</span> <span class="params">(item, i)</span> {</span>
    <span class="keyword">if</span> (item.path.indexOf(lastPath) !== <span class="number">0</span>) {
      lastPath = item.path + <span class="string">'.'</span>;
      minimal.push(item);
      top = item;
    } <span class="keyword">else</span> {
      <span class="keyword">if</span> (!(item.value &amp;&amp; top.value)) <span class="keyword">return</span>;

      <span class="comment">// special case for top level MongooseArrays</span>
      <span class="keyword">if</span> (top.value._atomics &amp;&amp; top.value.hasAtomics()) {
        <span class="comment">// the `top` array itself and a sub path of `top` are being modified.</span>
        <span class="comment">// the only way to honor all of both modifications is through a $set</span>
        <span class="comment">// of entire array.</span>
        top.value._atomics = {};
        top.value._atomics.$set = top.value;
      }
    }
  });

  top = lastPath = <span class="literal">null</span>;
  <span class="keyword">return</span> minimal;
}</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="document_Document-_setSchema"><a href="#document_Document-_setSchema">Document#_setSchema(<code>schema</code>)</a></h3><p>Assigns/compiles <code>schema</code> into this documents prototype.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype._setSchema = <span class="function"><span class="keyword">function</span> <span class="params">(schema)</span> {</span>
  compile(schema.tree, <span class="keyword">this</span>);
  <span class="keyword">this</span>.schema = schema;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>schema</code><span class="types"> &lt;<a href="#schema_Schema">Schema</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="document_Document-_registerHooks"><a href="#document_Document-_registerHooks">Document#_registerHooks()</a></h3><p>Register default hooks</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype._registerHooks = function _registerHooks () {
  if (!this.save) return;

  DocumentArray || (DocumentArray = require('./types/documentarray'));

  this.pre('save', function (next) {
    // we keep the error semaphore to make sure we don't
    // call `save` unnecessarily (we only need 1 error)
    var subdocs = 0
      , error = false
      , self = this;

    // check for DocumentArrays
    var arrays = this._activePaths
    .map('init', 'modify', function (i) {
      return self.getValue(i);
    })
    .filter(function (val) {
      return (val &amp;&amp; val instanceof DocumentArray &amp;&amp; val.length);
    });

    if (!arrays.length)
      return next();

    arrays.forEach(function (array) {
      subdocs += array.length;
      array.forEach(function (value) {
        if (error) return;

        value.save(function (err) {
          if (error) return;

          if (err) {
            error = true;
            self._validationError = undefined;
            return next(err);
          }

          --subdocs || next();
        });
      });
    });
  }, function (err) {
    // emit on the Model if listening
    if (this.constructor.listeners('error').length) {
      this.constructor.emit('error', err);
    } else {
      // emit on the connection
      if (!this.db.listeners('error').length) {
        err.stack = 'No listeners detected, throwing. '
                  + 'Consider adding an error listener to your connection.
'
                  + err.stack
      }
      this.db.emit('error', err);
    }
  }).pre('save', function checkForExistingErrors (next) {
    // if any doc.set() calls failed
    if (this._saveError) {
      next(this._saveError);
      this._saveError = null;
    } else {
      next();
    }
  }).pre('save', function validation (next) {
    return this.validate(next);
  });

  // add user defined queues
  this._doQueue();
};</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="document_Document-_error"><a href="#document_Document-_error">Document#_error(<code>err</code>)</a></h3><p>Registers an error</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype._error = <span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
  <span class="keyword">this</span>._saveError = err;
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>err</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error">Error</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="document_Document-_doQueue"><a href="#document_Document-_doQueue">Document#_doQueue()</a></h3><p>Executes methods queued from the Schema definition</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype._doQueue = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">var</span> q = <span class="keyword">this</span>.schema &amp;&amp; <span class="keyword">this</span>.schema.callQueue;
  <span class="keyword">if</span> (q) {
    <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>, l = q.length; i &lt; l; i++) {
      <span class="keyword">this</span>[q[i][<span class="number">0</span>]].apply(<span class="keyword">this</span>, q[i][<span class="number">1</span>]);
    }
  }
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="document_Document-toObject"><a href="#document_Document-toObject">Document#toObject(<code>[options]</code>)</a></h3><p>Converts this document into a plain javascript object</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype.toObject = <span class="function"><span class="keyword">function</span> <span class="params">(options)</span> {</span>
  <span class="comment">// When internally saving this document we always pass options,</span>
  <span class="comment">// bypassing the custom schema options.</span>
  <span class="keyword">if</span> (!(options &amp;&amp; <span class="string">'Object'</span> == options.constructor.name)) {
    options = <span class="keyword">this</span>.schema.options.toObject
      ? clone(<span class="keyword">this</span>.schema.options.toObject)
      : {};
  }

  ;(<span class="string">'minimize'</span> <span class="keyword">in</span> options) || (options.minimize = <span class="keyword">this</span>.schema.options.minimize);

  <span class="keyword">var</span> ret = clone(<span class="keyword">this</span>._doc, options);

  <span class="keyword">if</span> (options.virtuals || options.getters &amp;&amp; <span class="literal">false</span> !== options.virtuals) {
    applyGetters(<span class="keyword">this</span>, ret, <span class="string">'virtuals'</span>, options);
  }

  <span class="keyword">if</span> (options.getters) {
    applyGetters(<span class="keyword">this</span>, ret, <span class="string">'paths'</span>, options);
  }

  <span class="keyword">return</span> ret;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>[options]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>js object</span></li></ul></div><div class="description"><h4>Options:</h4>

<ul>
<li><code>getters</code> apply all getters (path and virtual getters)</li>
<li><code>virtuals</code> apply virtual getters (can override <code>getters</code> option)</li>
<li><code>minimize</code> remove empty objects (defaults to true)</li>
</ul>

<p>Example of only applying path getters</p>

<pre><code>doc.toObject({ getters: <span class="literal">true</span>, virtuals: <span class="literal">false</span> })</code></pre>

<p>Example of only applying virtual getters</p>

<pre><code>doc.toObject({ virtuals: <span class="literal">true</span> })</code></pre>

<p>Example of applying both path and virtual getters</p>

<pre><code>doc.toObject({ getters: <span class="literal">true</span> })</code></pre>

<p>To apply these options to every document of your schema by default, set your <a href="#schema_Schema">schemas</a> <code>toObject</code> option to the same argument.</p>

<pre><code>schema.set(<span class="string">'toObject'</span>, { virtuals: <span class="literal">true</span> })</code></pre>

<p>See <a href="./guide.html#toObject">schema options</a> for details.</p></div><hr class=""></div><div class="item method public"><h3 id="document_Document-toJSON"><a href="#document_Document-toJSON">Document#toJSON(<code>options</code>)</a></h3><p>The return value of this method is used in calls to JSON.stringify(doc).</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype.toJSON = <span class="function"><span class="keyword">function</span> <span class="params">(options)</span> {</span>
  <span class="comment">// check for object type since an array of documents</span>
  <span class="comment">// being stringified passes array indexes instead</span>
  <span class="comment">// of options objects. JSON.stringify([doc, doc])</span>
  <span class="keyword">if</span> (!(options &amp;&amp; <span class="string">'Object'</span> == options.constructor.name)) {
    options = <span class="keyword">this</span>.schema.options.toJSON
      ? clone(<span class="keyword">this</span>.schema.options.toJSON)
      : {};
  }
  options.json = <span class="literal">true</span>;
  <span class="keyword">return</span> <span class="keyword">this</span>.toObject(options);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>options</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>same options as `Document#toObject`</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="#document_Document-toObject" title="Document#toObject">Document#toObject</a></li></ul></div><div class="description"><p>This method accepts the same options as <a href="#document_Document-toObject">Document#toObject</a>. To apply the options to every document of your schema by default, set your <a href="#schema_Schema">schemas</a> <code>toJSON</code> option to the same argument.</p>

<pre><code>schema.set(<span class="string">'toJSON'</span>, { virtuals: <span class="literal">true</span> })</code></pre>

<p>See <a href="./guide.html#toJSON">schema options</a> for details.</p></div><hr class=""></div><div class="item method public"><h3 id="document_Document-inspect"><a href="#document_Document-inspect">Document#inspect()</a></h3><p>Helper for console.log</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype.inspect = <span class="function"><span class="keyword">function</span> <span class="params">(options)</span> {</span>
  <span class="keyword">var</span> opts = options &amp;&amp; <span class="string">'Object'</span> == options.constructor.name
    ? options
    : <span class="literal">undefined</span>
  <span class="keyword">return</span> inspect(<span class="keyword">this</span>.toObject(opts));
};</code></pre></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="document_Document-toString"><a href="#document_Document-toString">Document#toString()</a></h3><p>Helper for console.log</p><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="document_Document-equals"><a href="#document_Document-equals">Document#equals(<code>doc</code>)</a></h3><p>Returns true if the Document stores the same data as doc.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Document.prototype.equals = <span class="function"><span class="keyword">function</span> <span class="params">(doc)</span> {</span>
  <span class="keyword">var</span> tid = <span class="keyword">this</span>.get(<span class="string">'_id'</span>);
  <span class="keyword">var</span> docid = doc.get(<span class="string">'_id'</span>);
  <span class="keyword">return</span> tid.equals
    ? tid.equals(docid)
    : tid === docid;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>doc</code><span class="types"> &lt;<a href="#document_Document">Document</a>&gt; </span><span>a document to compare</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span></span></li></ul></div><div class="description"><p>Documents are considered equal when they have matching <code>_id</code>s.</p></div><hr class=""></div><div class="item property public"><h3 id="document_Document-errors"><a href="#document_Document-errors">Document#<span>errors</span></a></h3><p>Hash containing current validation errors.</p><hr class=""></div><div class="item property public"><h3 id="document_Document-id"><a href="#document_Document-id">Document#<span>id</span></a></h3><p>The string version of this documents _id.</p>

<h4>Note:</h4>

<p>This getter exists on all documents by default. The getter can be disabled by setting the <code>id</code> <a href="./guide.html#id">option</a> of its <code>Schema</code> to false at construction time.</p>

<pre><code><span class="keyword">new</span> Schema({ name: String }, { id: <span class="literal">false</span> });</code></pre><hr class=""></div><div class="item property public"><h3 id="document_Document-isNew"><a href="#document_Document-isNew">Document#<span>isNew</span></a></h3><p>Boolean flag specifying if the document is new.</p><hr class=""></div><div class="item property public"><h3 id="document_Document-schema"><a href="#document_Document-schema">Document#<span>schema</span></a></h3><p>The documents schema.</p><hr class=""></div></li><li class="module "><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/drivers/node-mongodb-native/collection.js" id="drivers-node-mongodb-native-collection-js">drivers/node-mongodb-native/collection.js</a><div class="item method private"><h3 id="drivers_node-mongodb-native_collection_NativeCollection"><a href="#drivers_node-mongodb-native_collection_NativeCollection">NativeCollection()</a></h3><p>A <a href="https://github.com/mongodb/node-mongodb-native">node-mongodb-native</a> collection implementation.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">NativeCollection</span> <span class="params">()</span> {</span>
  <span class="keyword">this</span>.collection = <span class="literal">null</span>;
  MongooseCollection.apply(<span class="keyword">this</span>, arguments);
}</code></pre></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="#collection_Collection">Collection</a></li></ul></div><div class="description"><p>All methods methods from the <a href="https://github.com/mongodb/node-mongodb-native">node-mongodb-native</a> driver are copied and wrapped in queue management.</p></div><hr class="private"></div><div class="item method private"><h3 id="drivers_node-mongodb-native_collection_NativeCollection-onOpen"><a href="#drivers_node-mongodb-native_collection_NativeCollection-onOpen">NativeCollection#onOpen()</a></h3><p>Called when the connection opens.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">NativeCollection.prototype.onOpen = function () {
  var self = this;

  if (this.collection) {
    return MongooseCollection.prototype.onOpen.call(self);
  }

  if (!self.opts.size) {
    // non-capped
    return self.conn.db.collection(self.name, callback);
  }

  // capped
  return self.conn.db.collection(self.name, function (err, c) {
    if (err) return callback(err);

    // discover if this collection exists and if it is capped
    c.options(function (err, exists) {
      if (err) return callback(err);

      if (exists) {
        if (exists.capped) {
          callback(null, c);
        } else {
          var msg = 'A non-capped collection exists with this name.

'
                  + ' To use this collection as a capped collection, please '
                  + 'first convert it.
'
                  + ' http://www.mongodb.org/display/DOCS/Capped+Collections#CappedCollections-Convertingacollectiontocapped'
          err = new Error(msg);
          callback(err);
        }
      } else {
        // create
        var opts = utils.clone(self.opts);
        opts.capped = true;
        self.conn.db.createCollection(self.name, opts, callback);
      }
    });
  });

  function callback (err, collection) {
    if (err) {
      // likely a strict mode error
      self.conn.emit('error', err);
    } else {
      self.collection = collection;
      MongooseCollection.prototype.onOpen.call(self);
    }
  };
};</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="drivers_node-mongodb-native_collection_NativeCollection-onClose"><a href="#drivers_node-mongodb-native_collection_NativeCollection-onClose">NativeCollection#onClose()</a></h3><p>Called when the connection closes</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">NativeCollection.prototype.onClose = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  MongooseCollection.prototype.onClose.call(<span class="keyword">this</span>);
};</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="drivers_node-mongodb-native_collection_NativeCollection-getIndexes"><a href="#drivers_node-mongodb-native_collection_NativeCollection-getIndexes">NativeCollection#getIndexes(<code>callback</code>)</a></h3><p>Retreives information about this collections indexes.</p><div class="params"><h4>Parameters:</h4><ul><li><code>callback</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class=""></div></li><li class="module private"><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/drivers/node-mongodb-native/connection.js" id="drivers-node-mongodb-native-connection-js">drivers/node-mongodb-native/connection.js</a><div class="item method private"><h3 id="drivers_node-mongodb-native_connection_NativeConnection"><a href="#drivers_node-mongodb-native_connection_NativeConnection">NativeConnection()</a></h3><p>A <a href="https://github.com/mongodb/node-mongodb-native">node-mongodb-native</a> connection implementation.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">NativeConnection</span><span class="params">()</span> {</span>
  MongooseConnection.apply(<span class="keyword">this</span>, arguments);
};</code></pre></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="#connection_Connection">Connection</a></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="drivers_node-mongodb-native_connection_NativeConnection-doOpen"><a href="#drivers_node-mongodb-native_connection_NativeConnection-doOpen">NativeConnection#doOpen(<code>fn</code>)</a></h3><p>Opens the connection to MongoDB.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">NativeConnection.prototype.doOpen = <span class="function"><span class="keyword">function</span> <span class="params">(fn)</span> {</span>
  <span class="keyword">var</span> server
    , self = <span class="keyword">this</span>;

  <span class="keyword">if</span> (!<span class="keyword">this</span>.db) {
    server = <span class="keyword">new</span> mongo.Server(<span class="keyword">this</span>.host, Number(<span class="keyword">this</span>.port), <span class="keyword">this</span>.options.server);
    <span class="keyword">this</span>.db = <span class="keyword">new</span> mongo.Db(<span class="keyword">this</span>.name, server, <span class="keyword">this</span>.options.db);
  }

  <span class="keyword">this</span>.db.open(<span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
    <span class="keyword">if</span> (err) <span class="keyword">return</span> fn(err);
    fn();
    listen(self);
  });

  <span class="keyword">return</span> <span class="keyword">this</span>;
};

<span class="function"><span class="keyword">function</span> <span class="title">listen</span> <span class="params">(conn)</span> {</span>
  <span class="keyword">if</span> (conn._listening) <span class="keyword">return</span>;
  conn._listening = <span class="literal">true</span>;

  conn.db.on(<span class="string">'close'</span>, <span class="keyword">function</span>(){
    <span class="keyword">if</span> (conn._closeCalled) <span class="keyword">return</span>;

    <span class="comment">// the driver never emits an `open` event. auto_reconnect still</span>
    <span class="comment">// emits a `close` event but since we never get another</span>
    <span class="comment">// `open` we can't emit close</span>
    <span class="keyword">if</span> (conn.db.serverConfig.autoReconnect) {
      conn.readyState = STATES.disconnected;
      conn.emit(<span class="string">'close'</span>);
      <span class="keyword">return</span>;
    }
    conn.onClose();
  });
  conn.db.on(<span class="string">'error'</span>, <span class="keyword">function</span>(err){
    conn.emit(<span class="string">'error'</span>, err);
  });
  conn.db.on(<span class="string">'timeout'</span>, <span class="keyword">function</span>(err){
    <span class="keyword">var</span> error = <span class="keyword">new</span> Error(err &amp;&amp; err.err || <span class="string">'connection timeout'</span>);
    conn.emit(<span class="string">'error'</span>, error);
  });
  conn.db.on(<span class="string">'open'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(err, db)</span> {</span>
    <span class="keyword">if</span> (STATES.disconnected === conn.readyState &amp;&amp; db &amp;&amp; db.databaseName) {
      conn.readyState = STATES.connected;
      conn.emit(<span class="string">'reconnected'</span>)
    }
  })
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>fn</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#connection_Connection">Connection</a>&gt; </span><span>this</span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="drivers_node-mongodb-native_connection_NativeConnection-doOpenSet"><a href="#drivers_node-mongodb-native_connection_NativeConnection-doOpenSet">NativeConnection#doOpenSet(<code>fn</code>)</a></h3><p>Opens a connection to a MongoDB ReplicaSet.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">NativeConnection.prototype.doOpenSet = <span class="function"><span class="keyword">function</span> <span class="params">(fn)</span> {</span>
  <span class="keyword">if</span> (!<span class="keyword">this</span>.db) {
    <span class="keyword">var</span> servers = []
      , ports = <span class="keyword">this</span>.port
      , self = <span class="keyword">this</span>

    <span class="keyword">this</span>.host.forEach(<span class="function"><span class="keyword">function</span> <span class="params">(host, i)</span> {</span>
      servers.push(<span class="keyword">new</span> mongo.Server(host, Number(ports[i]), self.options.server));
    });

    <span class="keyword">var</span> server = <span class="keyword">new</span> ReplSetServers(servers, <span class="keyword">this</span>.options.replset);
    <span class="keyword">this</span>.db = <span class="keyword">new</span> mongo.Db(<span class="keyword">this</span>.name, server, <span class="keyword">this</span>.options.db);

    <span class="keyword">this</span>.db.on(<span class="string">'fullsetup'</span>, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
      self.emit(<span class="string">'fullsetup'</span>)
    });
  }

  <span class="keyword">this</span>.db.open(<span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
    <span class="keyword">if</span> (err) <span class="keyword">return</span> fn(err);
    fn();
    listen(self);
  });

  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>fn</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#connection_Connection">Connection</a>&gt; </span><span>this</span></li></ul></div><div class="description"><p>See description of <a href="#NativeConnection-doOpen">doOpen</a> for server options. In this case <code>options.replset</code> is also passed to ReplSetServers.</p></div><hr class="private"></div><div class="item method private"><h3 id="drivers_node-mongodb-native_connection_NativeConnection-doClose"><a href="#drivers_node-mongodb-native_connection_NativeConnection-doClose">NativeConnection#doClose(<code>fn</code>)</a></h3><p>Closes the connection</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">NativeConnection.prototype.doClose = <span class="function"><span class="keyword">function</span> <span class="params">(fn)</span> {</span>
  <span class="keyword">this</span>.db.close();
  <span class="keyword">if</span> (fn) fn();
  <span class="keyword">return</span> <span class="keyword">this</span>;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>fn</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#connection_Connection">Connection</a>&gt; </span><span>this</span></li></ul></div><div class="description"></div><hr class="private"></div></li><li class="module private"><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/error.js" id="error-js">error.js</a><div class="item method private"><h3 id="error_MongooseError"><a href="#error_MongooseError">MongooseError()</a></h3><p>Mongoose error</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">MongooseError</span> <span class="params">(msg)</span> {</span>
  Error.call(<span class="keyword">this</span>);
  Error.captureStackTrace(<span class="keyword">this</span>, arguments.callee);
  <span class="keyword">this</span>.message = msg;
  <span class="keyword">this</span>.name = <span class="string">'MongooseError'</span>;
};</code></pre></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error" title="Error">Error</a></li></ul></div><div class="description"></div><hr class="private"></div></li><li class="module private"><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/errors/cast.js" id="errors-cast-js">errors/cast.js</a><div class="item method private"><h3 id="errors_cast_CastError"><a href="#errors_cast_CastError">CastError(<code>type</code>, <code>value</code>)</a></h3><p>Casting Error constructor.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">CastError</span> <span class="params">(type, value)</span> {</span>
  MongooseError.call(<span class="keyword">this</span>, <span class="string">'Cast to '</span> + type + <span class="string">' failed for value "'</span> + value + <span class="string">'"'</span>);
  Error.captureStackTrace(<span class="keyword">this</span>, arguments.callee);
  <span class="keyword">this</span>.name = <span class="string">'CastError'</span>;
  <span class="keyword">this</span>.type = type;
  <span class="keyword">this</span>.value = value;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>type</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>value</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li></ul></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="#error_MongooseError">MongooseError</a></li></ul></div><div class="description"></div><hr class="private"></div></li><li class="module private"><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/errors/document.js" id="errors-document-js">errors/document.js</a><div class="item method private"><h3 id="errors_document_DocumentError"><a href="#errors_document_DocumentError">DocumentError(<code>msg</code>)</a></h3><p>Document Error</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">DocumentError</span> <span class="params">(msg)</span> {</span>
  MongooseError.call(<span class="keyword">this</span>, msg);
  Error.captureStackTrace(<span class="keyword">this</span>, arguments.callee);
  <span class="keyword">this</span>.name = <span class="string">'DocumentError'</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>msg</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li></ul></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="#error_MongooseError">MongooseError</a></li></ul></div><div class="description"></div><hr class="private"></div></li><li class="module "><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/errors/validation.js" id="errors-validation-js">errors/validation.js</a><div class="item method private"><h3 id="errors_validation_ValidationError"><a href="#errors_validation_ValidationError">ValidationError(<code>instance</code>)</a></h3><p>Document Validation Error</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">ValidationError</span> <span class="params">(instance)</span> {</span>
  MongooseError.call(<span class="keyword">this</span>, <span class="string">"Validation failed"</span>);
  Error.captureStackTrace(<span class="keyword">this</span>, arguments.callee);
  <span class="keyword">this</span>.name = <span class="string">'ValidationError'</span>;
  <span class="keyword">this</span>.errors = instance.errors = {};
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>instance</code><span class="types"> &lt;<a href="#document_Document">Document</a>&gt; </span><span></span></li></ul></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="#error_MongooseError">MongooseError</a></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="errors_validation_ValidationError-toString"><a href="#errors_validation_ValidationError-toString">ValidationError#toString()</a></h3><p>Console.log helper</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">ValidationError.prototype.toString = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">return</span> <span class="keyword">this</span>.name + <span class="string">': '</span> + Object.keys(<span class="keyword">this</span>.errors).map(<span class="function"><span class="keyword">function</span> <span class="params">(key)</span> {</span>
    <span class="keyword">return</span> String(<span class="keyword">this</span>.errors[key]);
  }, <span class="keyword">this</span>).join(<span class="string">', '</span>);
};</code></pre></div><div class="description"></div><hr class=""></div></li><li class="module private"><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/errors/validator.js" id="errors-validator-js">errors/validator.js</a><div class="item method private"><h3 id="errors_validator_ValidatorError"><a href="#errors_validator_ValidatorError">ValidatorError(<code>path</code>, <code>msg</code>)</a></h3><p>Schema validator error</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">ValidatorError</span> <span class="params">(path, type)</span> {</span>
  <span class="keyword">var</span> msg = type
    ? <span class="string">'"'</span> + type + <span class="string">'" '</span>
    : <span class="string">''</span>;
  MongooseError.call(<span class="keyword">this</span>, <span class="string">'Validator '</span> + msg + <span class="string">'failed for path '</span> + path);
  Error.captureStackTrace(<span class="keyword">this</span>, arguments.callee);
  <span class="keyword">this</span>.name = <span class="string">'ValidatorError'</span>;
  <span class="keyword">this</span>.path = path;
  <span class="keyword">this</span>.type = type;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>msg</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li></ul></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="#error_MongooseError">MongooseError</a></li></ul></div><div class="description"></div><hr class="private"></div></li><li class="module "><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/model.js" id="model-js">model.js</a><div class="item method public"><h3 id="model_Model"><a href="#model_Model">Model(<code>doc</code>)</a></h3><p>Model constructor</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">Model</span> <span class="params">(doc, fields, skipId)</span> {</span>
  Document.call(<span class="keyword">this</span>, doc, fields, skipId);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>doc</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>values to with which to create the document</span></li></ul></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="#document_Document">Document</a></li></ul></div><div class="events"><h4>Events:</h4><ul><li><p><code>error</code>: If listening to this Model event, it is emitted when a document was saved without passing a callback and an <code>error</code> occurred. If not listening, the event bubbles to the connection used to create this Model.</p></li><li><p><code>index</code>: Emitted after <code>Model#ensureIndexes</code> completes. If an error occurred it is passed with the event.</p></li></ul></div><div class="description"></div><hr class=""></div><div class="item method private"><h3 id="model_Model-_getPopulationKeys"><a href="#model_Model-_getPopulationKeys">Model#_getPopulationKeys(<code>query</code>)</a></h3><p>Returns what paths can be populated</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.prototype._getPopulationKeys = <span class="function"><span class="keyword">function</span> <span class="title">getPopulationKeys</span> <span class="params">(query)</span> {</span>
  <span class="keyword">if</span> (!(query &amp;&amp; query.options.populate)) <span class="keyword">return</span>;

  <span class="keyword">var</span> names = Object.keys(query.options.populate)
    , n = names.length
    , name
    , paths = {}
    , hasKeys
    , schema

  <span class="keyword">while</span> (n--) {
    name = names[n];
    schema = <span class="keyword">this</span>.schema.path(name);
    hasKeys = <span class="literal">true</span>;

    <span class="keyword">if</span> (!schema) {
      <span class="comment">// if the path is not recognized, it's potentially embedded docs</span>
      <span class="comment">// walk path atoms from right to left to find a matching path</span>
      <span class="keyword">var</span> pieces = name.split(<span class="string">'.'</span>)
        , i = pieces.length;

      <span class="keyword">while</span> (i--) {
        <span class="keyword">var</span> path = pieces.slice(<span class="number">0</span>, i).join(<span class="string">'.'</span>)
          , pathSchema = <span class="keyword">this</span>.schema.path(path);

        <span class="comment">// loop until we find an array schema</span>
        <span class="keyword">if</span> (pathSchema &amp;&amp; pathSchema.caster) {
          <span class="keyword">if</span> (!paths[path]) {
            paths[path] = { sub: {} };
          }

          paths[path].sub[pieces.slice(i).join(<span class="string">'.'</span>)] = query.options.populate[name];
          hasKeys || (hasKeys = <span class="literal">true</span>);
          <span class="keyword">break</span>;
        }
      }
    } <span class="keyword">else</span> {
      paths[name] = query.options.populate[name];
      hasKeys || (hasKeys = <span class="literal">true</span>);
    }
  }

  <span class="keyword">return</span> hasKeys &amp;&amp; paths;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>query</code><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>object</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined">undefined</a>&gt; </span><span>population paths</span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="model_Model-_populate"><a href="#model_Model-_populate">Model#_populate(<code>schema</code>, <code>oid</code>, <code>query</code>, <code>fn</code>)</a></h3><p>Populates an object</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.prototype._populate = <span class="function"><span class="keyword">function</span> <span class="title">populate</span> <span class="params">(schema, oid, query, fn)</span> {</span>
  <span class="keyword">if</span> (!Array.isArray(oid)) {
    <span class="keyword">var</span> conditions = query.conditions || {};
    conditions._id = oid;

    <span class="keyword">return</span> <span class="keyword">this</span>
    .db.model(query.model || schema.options.ref)
    .findOne(conditions, query.fields, query.options, fn);
  }

  <span class="keyword">if</span> (!oid.length) {
    <span class="keyword">return</span> fn(<span class="literal">null</span>, oid);
  }

  <span class="keyword">var</span> model = <span class="keyword">this</span>.db.model(query.model || schema.caster.options.ref)
    , conditions = query &amp;&amp; query.conditions || {};

  conditions._id || (conditions._id = { $<span class="keyword">in</span>: oid });

  model.find(conditions, query.fields, query.options, <span class="function"><span class="keyword">function</span> <span class="params">(err, docs)</span> {</span>
    <span class="keyword">if</span> (err) <span class="keyword">return</span> fn(err);

    <span class="comment">// user specified sort order?</span>
    <span class="keyword">if</span> (query.options &amp;&amp; query.options.sort) {
      <span class="keyword">return</span> fn(<span class="literal">null</span>, docs);
    }

    <span class="comment">// put back in original id order (using a hash reduces complexity from n*n to 2n)</span>
    <span class="keyword">var</span> docHash = {};
    docs.forEach(<span class="function"><span class="keyword">function</span> <span class="params">(doc)</span> {</span>
      docHash[doc._id] = doc;
    });

    <span class="keyword">var</span> arr = [];
    oid.forEach(<span class="function"><span class="keyword">function</span> <span class="params">(id)</span> {</span>
      <span class="keyword">if</span> (id <span class="keyword">in</span> docHash) arr.push(docHash[id]);
    });

    fn(<span class="literal">null</span>, arr);
  });
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>schema</code><span class="types"> &lt;<a href="#schematype_SchemaType">SchemaType</a>&gt; </span><span>type for the oid</span></li><li><code>oid</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>object id or array of object ids</span></li><li><code>query</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>object specifying query conditions, fields, and options</span></li><li><code>fn</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="model_Model-init"><a href="#model_Model-init">Model#init(<code>doc</code>, <code>query</code>, <code>fn</code>)</a></h3><p>Performs auto-population of relations.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.prototype.init = <span class="function"><span class="keyword">function</span> <span class="title">init</span> <span class="params">(doc, query, fn)</span> {</span>
  <span class="keyword">if</span> (<span class="string">'function'</span> == <span class="keyword">typeof</span> query) {
    fn = query;
    query = <span class="literal">null</span>;
  }

  <span class="keyword">var</span> populate = <span class="keyword">this</span>._getPopulationKeys(query);

  <span class="keyword">if</span> (!populate) {
    <span class="keyword">return</span> Document.prototype.init.call(<span class="keyword">this</span>, doc, fn);
  }

  <span class="comment">// population from other models is necessary</span>
  <span class="keyword">var</span> self = <span class="keyword">this</span>;

  init(doc, <span class="string">''</span>, <span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
    <span class="keyword">if</span> (err) <span class="keyword">return</span> fn(err);
    Document.prototype.init.call(self, doc, fn);
  });

  <span class="keyword">return</span> <span class="keyword">this</span>;

  <span class="function"><span class="keyword">function</span> <span class="title">init</span> <span class="params">(obj, prefix, fn)</span> {</span>
    prefix = prefix || <span class="string">''</span>;

    <span class="keyword">var</span> keys = Object.keys(obj)
      , len = keys.length;

    <span class="keyword">return</span> next();

    <span class="function"><span class="keyword">function</span> <span class="title">next</span> <span class="params">()</span> {</span>
      <span class="keyword">if</span> (--len &lt; <span class="number">0</span>) <span class="keyword">return</span> fn();

      <span class="keyword">var</span> i = keys[len]
        , path = prefix + i
        , schema = self.schema.path(path)
        , total = <span class="number">0</span>
        , inline = <span class="literal">false</span>
        , poppath

      <span class="keyword">if</span> (!schema &amp;&amp; obj[i] &amp;&amp; <span class="string">'Object'</span> === obj[i].constructor.name) {
        <span class="comment">// assume nested object</span>
        <span class="keyword">return</span> init(obj[i], path + <span class="string">'.'</span>, next);
      }

      <span class="keyword">if</span> (!(obj[i] &amp;&amp; schema &amp;&amp; populate[path])) <span class="keyword">return</span> next();

      <span class="comment">// this query object is re-used and passed around. we clone</span>
      <span class="comment">// it to prevent query condition contamination between</span>
      <span class="comment">// one populate call to the next.</span>
      poppath = utils.clone(populate[path]);

      <span class="keyword">if</span> (poppath.sub) {
        obj[i].forEach(<span class="function"><span class="keyword">function</span> <span class="params">(subobj)</span> {</span>
          inline = <span class="literal">true</span>;

          <span class="keyword">var</span> pkeys = Object.keys(poppath.sub)
            , pi = pkeys.length
            , key

          <span class="keyword">while</span> (pi--) {
            key = pkeys[pi];

            <span class="keyword">if</span> (subobj[key]) (<span class="function"><span class="keyword">function</span> <span class="params">(key)</span> {</span>
              total++;
              self._populate(schema.schema.path(key), subobj[key], poppath.sub[key], done);
              <span class="function"><span class="keyword">function</span> <span class="title">done</span> <span class="params">(err, doc)</span> {</span>
                <span class="keyword">if</span> (err) <span class="keyword">return</span> error(err);
                subobj[key] = doc;
                <span class="keyword">if</span> (--total &lt; <span class="number">1</span> &amp;&amp; !inline) {
                  next();
                }
              }
            })(key);
          }
        });

        inline = <span class="literal">false</span>;

        <span class="keyword">if</span> (<span class="number">0</span> === total) <span class="keyword">return</span> next();

      } <span class="keyword">else</span> {
        self._populate(schema, obj[i], poppath, <span class="function"><span class="keyword">function</span> <span class="params">(err, doc)</span> {</span>
          <span class="keyword">if</span> (err) <span class="keyword">return</span> error(err);
          obj[i] = doc;
          next();
        });
      }
    };
  };

  <span class="function"><span class="keyword">function</span> <span class="title">error</span> <span class="params">(err)</span> {</span>
    <span class="keyword">if</span> (error.err) <span class="keyword">return</span>;
    fn(error.err = err);
  }
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>doc</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>document returned by mongo</span></li><li><code>query</code><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>query that originated the initialization</span></li><li><code>fn</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="model_Model-save"><a href="#model_Model-save">Model#save(<code>[fn]</code>)</a></h3><p>Saves this document.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.prototype.save = <span class="function"><span class="keyword">function</span> <span class="title">save</span> <span class="params">(fn)</span> {</span>
  <span class="keyword">var</span> promise = <span class="keyword">new</span> Promise(fn)
    , complete = handleSave(promise, <span class="keyword">this</span>)
    , options = {}

  <span class="keyword">if</span> (<span class="keyword">this</span>.schema.options.safe) {
    options.safe = <span class="keyword">this</span>.schema.options.safe;
  }

  <span class="keyword">if</span> (<span class="keyword">this</span>.isNew) {
    <span class="comment">// send entire doc</span>
    <span class="keyword">var</span> obj = <span class="keyword">this</span>.toObject({ depopulate: <span class="number">1</span> });
    <span class="keyword">this</span>._version(<span class="literal">true</span>, obj);
    <span class="keyword">this</span>.collection.insert(obj, options, complete);
    <span class="keyword">this</span>._reset();
    <span class="keyword">this</span>.isNew = <span class="literal">false</span>;
    <span class="keyword">this</span>.emit(<span class="string">'isNew'</span>, <span class="literal">false</span>);
    <span class="comment">// Make it possible to retry the insert</span>
    <span class="keyword">this</span>._inserting = <span class="literal">true</span>;

  } <span class="keyword">else</span> {
    <span class="comment">// Make sure we don't treat it as a new object on error,</span>
    <span class="comment">// since it already exists</span>
    <span class="keyword">this</span>._inserting = <span class="literal">false</span>;

    <span class="keyword">var</span> delta = <span class="keyword">this</span>._delta();
    <span class="keyword">if</span> (delta) {
      <span class="keyword">var</span> where = <span class="keyword">this</span>._where(delta[<span class="number">0</span>]);
      <span class="keyword">this</span>.collection.update(where, delta[<span class="number">1</span>], options, complete);
    } <span class="keyword">else</span> {
      complete(<span class="literal">null</span>);
    }

    <span class="keyword">this</span>._reset();
    <span class="keyword">this</span>.emit(<span class="string">'isNew'</span>, <span class="literal">false</span>);
  }
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>[fn]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span>optional callback</span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://mongoosejs.com./middleware.html" title="middleware">middleware</a></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code>product.sold = Date.now();
product.save(<span class="function"><span class="keyword">function</span> <span class="params">(err, product)</span> {</span>
  <span class="keyword">if</span> (err) ..
})</code></pre>

<p>The <code>fn</code> callback is optional. If no <code>fn</code> is passed and validation fails, the validation error will be emitted on the connection used to create this model.</p>

<pre><code><span class="keyword">var</span> db = mongoose.createConnection(..);
<span class="keyword">var</span> schema = <span class="keyword">new</span> Schema(..);
<span class="keyword">var</span> Product = db.model(<span class="string">'Product'</span>, schema);

db.on(<span class="string">'error'</span>, handleError);</code></pre>

<p>However, if you desire more local error handling you can add an <code>error</code> listener to the model and handle errors there instead.</p>

<pre><code>Product.on(<span class="string">'error'</span>, handleError);</code></pre></div><hr class=""></div><div class="item method private"><h3 id="model_Model-_delta"><a href="#model_Model-_delta">Model#_delta()</a></h3><p>Produces a special query document of the modified properties used in updates.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.prototype._delta = <span class="function"><span class="keyword">function</span> <span class="title">_delta</span> <span class="params">()</span> {</span>
  <span class="keyword">var</span> dirty = <span class="keyword">this</span>._dirty();
  <span class="keyword">if</span> (!dirty.length) <span class="keyword">return</span>;

  <span class="keyword">var</span> self = <span class="keyword">this</span>
    , where = {}
    , delta = {}
    , len = dirty.length
    , d = <span class="number">0</span>
    , val
    , obj

  <span class="keyword">for</span> (; d &lt; len; ++d) {
    <span class="keyword">var</span> data = dirty[d]
    <span class="keyword">var</span> value = data.value
    <span class="keyword">var</span> schema = data.schema

    <span class="keyword">if</span> (<span class="literal">undefined</span> === value) {
      operand(self, where, delta, data, <span class="number">1</span>, <span class="string">'$unset'</span>);

    } <span class="keyword">else</span> <span class="keyword">if</span> (<span class="literal">null</span> === value) {
      operand(self, where, delta, data, <span class="literal">null</span>);

    } <span class="keyword">else</span> <span class="keyword">if</span> (value._path &amp;&amp; value._atomics) {
      handleAtomics(self, where, delta, data, value);

    } <span class="keyword">else</span> <span class="keyword">if</span> (value._path &amp;&amp; Buffer.isBuffer(value)) {
      <span class="comment">// MongooseBuffer</span>
      value = value.toObject();
      operand(self, where, delta, data, value);

    } <span class="keyword">else</span> {
      value = utils.clone(value);
      operand(self, where, delta, data, value);
    }
  }

  <span class="keyword">if</span> (<span class="keyword">this</span>.__version) {
    <span class="keyword">this</span>._version(where, delta);
  }

  <span class="keyword">return</span> [where, delta];
}</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="model_Model-_version"><a href="#model_Model-_version">Model#_version()</a></h3><p>Appends versioning to the where and update clauses.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.prototype._version = <span class="function"><span class="keyword">function</span> <span class="title">_version</span> <span class="params">(where, delta)</span> {</span>
  <span class="keyword">var</span> key = <span class="keyword">this</span>.schema.options.versionKey;

  <span class="keyword">if</span> (<span class="literal">true</span> === where) {
    <span class="comment">// this is an insert</span>
    <span class="keyword">if</span> (key) <span class="keyword">this</span>.setValue(key, delta[key] = <span class="number">0</span>);
    <span class="keyword">return</span>;
  }

  <span class="comment">// updates</span>

  <span class="comment">// only apply versioning if our versionKey was selected. else</span>
  <span class="comment">// there is no way to select the correct version. we could fail</span>
  <span class="comment">// fast here and force them to include the versionKey but</span>
  <span class="comment">// thats a bit intrusive. can we do this automatically?</span>
  <span class="comment">// TODO fail fast option?</span>
  <span class="keyword">if</span> (!<span class="keyword">this</span>.isSelected(key)) {
    <span class="keyword">return</span>;
  }

  <span class="comment">// $push $addToSet don't need the where clause set</span>
  <span class="keyword">if</span> (VERSION_WHERE === (VERSION_WHERE &amp; <span class="keyword">this</span>.__version)) {
    where[key] = <span class="keyword">this</span>.getValue(key);
  }

  <span class="keyword">if</span> (VERSION_INC === (VERSION_INC &amp; <span class="keyword">this</span>.__version)) {
    delta.$inc || (delta.$inc = {});
    delta.$inc[key] = <span class="number">1</span>;
  }
}</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="model_Model-increment"><a href="#model_Model-increment">Model#increment()</a></h3><p>Signal that we desire an increment of this documents version.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.prototype.increment = <span class="function"><span class="keyword">function</span> <span class="title">increment</span> <span class="params">()</span> {</span>
  <span class="keyword">this</span>.__version = VERSION_ALL;
  <span class="keyword">return</span> <span class="keyword">this</span>;
}</code></pre></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://mongoosejs.com./guide.html#versionKey" title="versionKeys">versionKeys</a></li></ul></div><div class="description"></div><hr class=""></div><div class="item method private"><h3 id="model_Model-_where"><a href="#model_Model-_where">Model#_where()</a></h3><p>Returns a query object which applies shardkeys if they exist.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.prototype._where = <span class="function"><span class="keyword">function</span> <span class="title">_where</span> <span class="params">(where)</span> {</span>
  where || (where = {});

  <span class="keyword">var</span> paths
    , len

  <span class="keyword">if</span> (<span class="keyword">this</span>._shardval) {
    paths = Object.keys(<span class="keyword">this</span>._shardval)
    len = paths.length

    <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; len; ++i) {
      where[paths[i]] = <span class="keyword">this</span>._shardval[paths[i]];
    }
  }

  where._id = <span class="keyword">this</span>._doc._id;
  <span class="keyword">return</span> where;
}</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="model_Model-remove"><a href="#model_Model-remove">Model#remove(<code>[fn]</code>)</a></h3><p>Removes this document from the db.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.prototype.remove = <span class="function"><span class="keyword">function</span> <span class="title">remove</span> <span class="params">(fn)</span> {</span>
  <span class="keyword">if</span> (<span class="keyword">this</span>._removing) <span class="keyword">return</span> <span class="keyword">this</span>;

  <span class="keyword">var</span> promise = <span class="keyword">this</span>._removing = <span class="keyword">new</span> Promise(fn)
    , where = <span class="keyword">this</span>._where()
    , self = <span class="keyword">this</span>
    , options = {}

  <span class="keyword">if</span> (<span class="keyword">this</span>.schema.options.safe) {
    options.safe = <span class="keyword">this</span>.schema.options.safe;
  }

  <span class="keyword">this</span>.collection.remove(where, options, tick(<span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
    <span class="keyword">if</span> (err) {
      promise.error(err);
      promise = self = self._removing = where = options = <span class="literal">null</span>;
      <span class="keyword">return</span>;
    }
    self.emit(<span class="string">'remove'</span>, self);
    promise.complete();
    promise = self = where = options = <span class="literal">null</span>;
  }));

  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>[fn]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span>optional callback</span></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code>product.remove(<span class="function"><span class="keyword">function</span> <span class="params">(err, product)</span> {</span>
  <span class="keyword">if</span> (err) <span class="keyword">return</span> handleError(err);
  Product.findById(product._id, <span class="function"><span class="keyword">function</span> <span class="params">(err, product)</span> {</span>
    console.log(product) <span class="comment">// null</span>
  })
})</code></pre></div><hr class=""></div><div class="item method private"><h3 id="model_Model-_registerHooks"><a href="#model_Model-_registerHooks">Model#_registerHooks()</a></h3><p>Register hooks override</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.prototype._registerHooks = <span class="function"><span class="keyword">function</span> <span class="title">registerHooks</span> <span class="params">()</span> {</span>
  Document.prototype._registerHooks.call(<span class="keyword">this</span>);
};</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="model_Model-model"><a href="#model_Model-model">Model#model(<code>name</code>)</a></h3><p>Returns another Model instance.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.prototype.model = <span class="function"><span class="keyword">function</span> <span class="title">model</span> <span class="params">(name)</span> {</span>
  <span class="keyword">return</span> <span class="keyword">this</span>.db.model(name);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>name</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>model name</span></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code><span class="keyword">var</span> doc = <span class="keyword">new</span> Tank;
doc.model(<span class="string">'User'</span>).findById(id, callback);</code></pre></div><hr class=""></div><div class="item method public"><h3 id="model_Model-%24where"><a href="#model_Model-%24where">Model#$where(<code>argument</code>)</a></h3><p>Creates a <code>Query</code> and specifies a <code>$where</code> condition.</p><div class="params"><h4>Parameters:</h4><ul><li><code>argument</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span>is a javascript string or anonymous function</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span></span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="#query_Query-%24where" title="Query.$where">Query.$where</a></li></ul></div><div class="description"><p>Sometimes you need to query for things in mongodb using a JavaScript expression. You can do so via <code>find({ $where: javascript })</code>, or you can use the mongoose shortcut method $where via a Query chain or from your mongoose Model.</p>

<pre><code>Blog.$where(<span class="string">'this.comments.length &amp;gt; 5'</span>);</code></pre></div><hr class=""></div><div class="item static private"><h3 id="model_Model-init"><a href="#model_Model-init">Model.init()</a></h3><p>Called when the model compiles.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.init = <span class="function"><span class="keyword">function</span> <span class="title">init</span> <span class="params">()</span> {</span>
  <span class="keyword">if</span> (<span class="keyword">this</span>.schema.options.autoIndex)
    <span class="keyword">this</span>.ensureIndexes();

  <span class="keyword">this</span>.schema.emit(<span class="string">'init'</span>, <span class="keyword">this</span>);
};</code></pre></div><hr class="private"></div><div class="item static public"><h3 id="model_Model-ensureIndexes"><a href="#model_Model-ensureIndexes">Model.ensureIndexes(<code>[cb]</code>)</a></h3><p>Sends <code>ensureIndex</code> commands to mongo for each index declared in the schema.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.ensureIndexes = <span class="function"><span class="keyword">function</span> <span class="title">ensureIndexes</span> <span class="params">(cb)</span> {</span>
  <span class="keyword">var</span> indexes = <span class="keyword">this</span>.schema.indexes();
  <span class="keyword">if</span> (!indexes.length) {
    <span class="keyword">return</span> cb &amp;&amp; cb();
  }

  <span class="keyword">var</span> self = <span class="keyword">this</span>
    , safe = self.schema.options.safe
    , count = indexes.length
    , error

  indexes.forEach(<span class="function"><span class="keyword">function</span> <span class="params">(index)</span> {</span>
    <span class="keyword">var</span> options = index[<span class="number">1</span>];
    options.safe = safe;
    self.collection.ensureIndex(index[<span class="number">0</span>], options, tick(<span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
      <span class="keyword">if</span> (err) error = err;
      <span class="keyword">if</span> (--count) <span class="keyword">return</span>;

      self.emit(<span class="string">'index'</span>, error);
      cb &amp;&amp; cb(error);
    }));
  });
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>[cb]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span>optional callback</span></li></ul></div><p>After completion, an <code>index</code> event is emitted on this <code>Model</code> passing an error if one occurred.</p><hr class=""></div><div class="item static public"><h3 id="model_Model-remove"><a href="#model_Model-remove">Model.remove(<code>conditions</code>, <code>[callback]</code>)</a></h3><p>Removes documents from the collection.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.remove = <span class="function"><span class="keyword">function</span> <span class="title">remove</span> <span class="params">(conditions, callback)</span> {</span>
  <span class="keyword">if</span> (<span class="string">'function'</span> === <span class="keyword">typeof</span> conditions) {
    callback = conditions;
    conditions = {};
  }

  <span class="keyword">var</span> query = <span class="keyword">new</span> Query(conditions).bind(<span class="keyword">this</span>, <span class="string">'remove'</span>);

  <span class="keyword">if</span> (<span class="string">'undefined'</span> === <span class="keyword">typeof</span> callback)
    <span class="keyword">return</span> query;

  <span class="keyword">this</span>._applyNamedScope(query);
  <span class="keyword">return</span> query.remove(callback);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>conditions</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[callback]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span></span></li></ul></div><h4>Note:</h4>

<p>To remove documents without waiting for a response from MongoDB, do not pass a <code>callback</code>, then call <code>exec</code> on the returned <a href="#query-js">Query</a>:</p>

<pre><code>Comment.remove({ _id: id }).exec();</code></pre><hr class=""></div><div class="item static public"><h3 id="model_Model-find"><a href="#model_Model-find">Model.find(<code>conditions</code>, <code>[fields]</code>, <code>[options]</code>, <code>[callback]</code>)</a></h3><p>Finds documents</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.find = <span class="function"><span class="keyword">function</span> <span class="title">find</span> <span class="params">(conditions, fields, options, callback)</span> {</span>
  <span class="keyword">if</span> (<span class="string">'function'</span> == <span class="keyword">typeof</span> conditions) {
    callback = conditions;
    conditions = {};
    fields = <span class="literal">null</span>;
    options = <span class="literal">null</span>;
  } <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">'function'</span> == <span class="keyword">typeof</span> fields) {
    callback = fields;
    fields = <span class="literal">null</span>;
    options = <span class="literal">null</span>;
  } <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">'function'</span> == <span class="keyword">typeof</span> options) {
    callback = options;
    options = <span class="literal">null</span>;
  }

  <span class="keyword">var</span> query = <span class="keyword">new</span> Query(conditions, options);
  query.bind(<span class="keyword">this</span>, <span class="string">'find'</span>);
  query.select(fields);

  <span class="keyword">if</span> (<span class="string">'undefined'</span> === <span class="keyword">typeof</span> callback)
    <span class="keyword">return</span> query;

  <span class="keyword">this</span>._applyNamedScope(query);
  <span class="keyword">return</span> query.find(callback);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>conditions</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[fields]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>optional fields to select</span></li><li><code>[options]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>optional</span></li><li><code>[callback]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span></span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="#query_Query-select" title="field selection">field selection</a></li></ul></div><h4>Examples:</h4>

<pre><code><span class="comment">// retrieve only certain keys</span>
MyModel.find({ name: <span class="regexp">/john/i</span> }, <span class="string">'name friends'</span>, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span> })

<span class="comment">// pass options</span>
MyModel.find({ name: <span class="regexp">/john/i</span> }, <span class="literal">null</span>, { skip: <span class="number">10</span> } )</code></pre><hr class=""></div><div class="item static private"><h3 id="model_Model-_applyNamedScope"><a href="#model_Model-_applyNamedScope">Model._applyNamedScope(<code>query</code>)</a></h3><p>Merges the current named scope query into <code>query</code>.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model._applyNamedScope = <span class="function"><span class="keyword">function</span> <span class="title">_applyNamedScope</span> <span class="params">(query)</span> {</span>
  <span class="keyword">var</span> cQuery = <span class="keyword">this</span>._cumulativeQuery;

  <span class="keyword">if</span> (cQuery) {
    merge(query._conditions, cQuery._conditions);
    <span class="keyword">if</span> (query._fields &amp;&amp; cQuery._fields)
      merge(query._fields, cQuery._fields);
    <span class="keyword">if</span> (query.options &amp;&amp; cQuery.options)
      merge(query.options, cQuery.options);
    <span class="keyword">delete</span> <span class="keyword">this</span>._cumulativeQuery;
  }

  <span class="keyword">return</span> query;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>query</code><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span></span></li></ul></div><hr class="private"></div><div class="item static public"><h3 id="model_Model-findById"><a href="#model_Model-findById">Model.findById(<code>id</code>, <code>[fields]</code>, <code>[options]</code>, <code>[callback]</code>)</a></h3><p>Finds a single document by id.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.findById = <span class="function"><span class="keyword">function</span> <span class="title">findById</span> <span class="params">(id, fields, options, callback)</span> {</span>
  <span class="keyword">return</span> <span class="keyword">this</span>.findOne({ _id: id }, fields, options, callback);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>id</code><span class="types"> &lt;<a href="#types_objectid_ObjectId">ObjectId</a>, <a href="#HexId">HexId</a>&gt; </span><span>objectid, or a value that can be casted to one</span></li><li><code>[fields]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>optional fields to select</span></li><li><code>[options]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>optional</span></li><li><code>[callback]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span></span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="#query_Query-select" title="field selection">field selection</a></li></ul></div><p>The <code>id</code> is cast to an ObjectId before sending the command.</p>

<h4>Example:</h4>

<pre><code>Adventure.findById(id, callback);</code></pre><hr class=""></div><div class="item static public"><h3 id="model_Model-findOne"><a href="#model_Model-findOne">Model.findOne(<code>conditions</code>, <code>[fields]</code>, <code>[options]</code>, <code>[callback]</code>)</a></h3><p>Finds one document.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.findOne = <span class="function"><span class="keyword">function</span> <span class="title">findOne</span> <span class="params">(conditions, fields, options, callback)</span> {</span>
  <span class="keyword">if</span> (<span class="string">'function'</span> == <span class="keyword">typeof</span> options) {
    <span class="comment">// TODO Handle all 3 of the following scenarios</span>
    <span class="comment">// Hint: Only some of these scenarios are possible if cQuery is present</span>
    <span class="comment">// Scenario: findOne(conditions, fields, callback);</span>
    <span class="comment">// Scenario: findOne(fields, options, callback);</span>
    <span class="comment">// Scenario: findOne(conditions, options, callback);</span>
    callback = options;
    options = <span class="literal">null</span>;
  } <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">'function'</span> == <span class="keyword">typeof</span> fields) {
    <span class="comment">// TODO Handle all 2 of the following scenarios</span>
    <span class="comment">// Scenario: findOne(conditions, callback)</span>
    <span class="comment">// Scenario: findOne(fields, callback)</span>
    <span class="comment">// Scenario: findOne(options, callback);</span>
    callback = fields;
    fields = <span class="literal">null</span>;
    options = <span class="literal">null</span>;
  } <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">'function'</span> == <span class="keyword">typeof</span> conditions) {
    callback = conditions;
    conditions = {};
    fields = <span class="literal">null</span>;
    options = <span class="literal">null</span>;
  }

  <span class="keyword">var</span> query = <span class="keyword">new</span> Query(conditions, options).select(fields).bind(<span class="keyword">this</span>, <span class="string">'findOne'</span>);

  <span class="keyword">if</span> (<span class="string">'undefined'</span> == <span class="keyword">typeof</span> callback)
    <span class="keyword">return</span> query;

  <span class="keyword">this</span>._applyNamedScope(query);
  <span class="keyword">return</span> query.findOne(callback);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>conditions</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[fields]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>optional fields to select</span></li><li><code>[options]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>optional</span></li><li><code>[callback]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span></span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="#query_Query-select" title="field selection">field selection</a></li></ul></div><p>The <code>conditions</code> are cast to their respective SchemaTypes before the command is sent.</p>

<h4>Example:</h4>

<pre><code>Adventure.findOne({ type: <span class="string">'iphone'</span> }, <span class="string">'name'</span>, { safe: <span class="literal">true</span> }, callback);</code></pre><hr class=""></div><div class="item static public"><h3 id="model_Model-count"><a href="#model_Model-count">Model.count(<code>conditions</code>, <code>[callback]</code>)</a></h3><p>Counts number of matching documents in a database collection.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.count = <span class="function"><span class="keyword">function</span> <span class="title">count</span> <span class="params">(conditions, callback)</span> {</span>
  <span class="keyword">if</span> (<span class="string">'function'</span> === <span class="keyword">typeof</span> conditions)
    callback = conditions, conditions = {};

  <span class="keyword">var</span> query = <span class="keyword">new</span> Query(conditions).bind(<span class="keyword">this</span>, <span class="string">'count'</span>);
  <span class="keyword">if</span> (<span class="string">'undefined'</span> == <span class="keyword">typeof</span> callback)
    <span class="keyword">return</span> query;

  <span class="keyword">this</span>._applyNamedScope(query);
  <span class="keyword">return</span> query.count(callback);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>conditions</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[callback]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span></span></li></ul></div><h4>Example:</h4>

<pre><code>Adventure.count({ type: <span class="string">'jungle'</span> }, <span class="function"><span class="keyword">function</span> <span class="params">(err, count)</span> {</span>
  <span class="keyword">if</span> (err) ..
  console.log(<span class="string">'there are %d jungle adventures'</span>, count);
});</code></pre><hr class=""></div><div class="item static public"><h3 id="model_Model-distinct"><a href="#model_Model-distinct">Model.distinct(<code>field</code>, <code>[conditions]</code>, <code>[callback]</code>)</a></h3><p>Executes a DISTINCT command</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.distinct = <span class="function"><span class="keyword">function</span> <span class="title">distinct</span> <span class="params">(field, conditions, callback)</span> {</span>
  <span class="keyword">var</span> query = <span class="keyword">new</span> Query(conditions).bind(<span class="keyword">this</span>, <span class="string">'distinct'</span>);
  <span class="keyword">if</span> (<span class="string">'undefined'</span> == <span class="keyword">typeof</span> callback) {
    query._distinctArg = field;
    <span class="keyword">return</span> query;
  }

  <span class="keyword">this</span>._applyNamedScope(query);
  <span class="keyword">return</span> query.distinct(field, callback);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>field</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>[conditions]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>optional</span></li><li><code>[callback]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span></span></li></ul></div><hr class=""></div><div class="item static public"><h3 id="model_Model-where"><a href="#model_Model-where">Model.where(<code>path</code>, <code>[val]</code>)</a></h3><p>Creates a Query, applies the passed conditions, and returns the Query.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.where = <span class="function"><span class="keyword">function</span> <span class="title">where</span> <span class="params">(path, val)</span> {</span>
  <span class="keyword">var</span> q = <span class="keyword">new</span> Query().bind(<span class="keyword">this</span>, <span class="string">'find'</span>);
  <span class="keyword">return</span> q.where.apply(q, arguments);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>[val]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>optional value</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span></span></li></ul></div><p>For example, instead of writing:</p>

<pre><code>User.find({age: {$gte: <span class="number">21</span>, $lte: <span class="number">65</span>}}, callback);</code></pre>

<p>we can instead write:</p>

<pre><code>User.where(<span class="string">'age'</span>).gte(<span class="number">21</span>).lte(<span class="number">65</span>).exec(callback);</code></pre>

<p>Since the Query class also supports <code>where</code> you can continue chaining</p>

<pre><code>User
.where(<span class="string">'age'</span>).gte(<span class="number">21</span>).lte(<span class="number">65</span>)
.where(<span class="string">'name'</span>, <span class="regexp">/^b/i</span>)
... etc</code></pre><hr class=""></div><div class="item static public"><h3 id="model_Model-findOneAndUpdate"><a href="#model_Model-findOneAndUpdate">Model.findOneAndUpdate(<code>[conditions]</code>, <code>[update]</code>, <code>[options]</code>, <code>[callback]</code>)</a></h3><p>Issues a mongodb findAndModify update command.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.findOneAndUpdate = function (conditions, update, options, callback) {
  if ('function' == typeof options) {
    callback = options;
    options = null;
  }
  else if (1 === arguments.length) {
    if ('function' == typeof conditions) {
      var msg = 'Model.findOneAndUpdate(): First argument must not be a function.

'
              + '  ' + this.modelName + '.findOneAndUpdate(conditions, update, options, callback)
'
              + '  ' + this.modelName + '.findOneAndUpdate(conditions, update, options)
'
              + '  ' + this.modelName + '.findOneAndUpdate(conditions, update)
'
              + '  ' + this.modelName + '.findOneAndUpdate(update)
'
              + '  ' + this.modelName + '.findOneAndUpdate()
';
      throw new TypeError(msg)
    }
    update = conditions;
    conditions = undefined;
  }

  var fields;
  if (options &amp;&amp; options.fields) {
    fields = options.fields;
    options.fields = undefined;
  }

  var query = new Query(conditions);
  query.setOptions(options);
  query.select(fields);
  query.bind(this, 'findOneAndUpdate', update);

  if ('undefined' == typeof callback)
    return query;

  this._applyNamedScope(query);
  return query.findOneAndUpdate(callback);
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>[conditions]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[update]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[options]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[callback]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span></span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/findAndModify+Command" title="mongodb">mongodb</a></li></ul></div><p>Finds a matching document, updates it according to the <code>update</code> arg, passing any <code>options</code>, and returns the found document (if any) to the callback. The query executes immediately if <code>callback</code> is passed else a Query object is returned.</p>

<h4>Options:</h4>

<ul>
<li><code>new</code>: bool - true to return the modified document rather than the original. defaults to true</li>
<li><code>upsert</code>: bool - creates the object if it doesn't exist. defaults to false.</li>
<li><code>sort</code>: if multiple docs are found by the conditions, sets the sort order to choose which doc to update</li>
<li><code>select</code>: sets the document fields to return</li>
</ul>

<h4>Examples:</h4>

<pre><code>A.findOneAndUpdate(conditions, update, options, callback) <span class="comment">// executes</span>
A.findOneAndUpdate(conditions, update, options)  <span class="comment">// returns Query</span>
A.findOneAndUpdate(conditions, update, callback) <span class="comment">// executes</span>
A.findOneAndUpdate(conditions, update)           <span class="comment">// returns Query</span>
A.findOneAndUpdate()                             <span class="comment">// returns Query</span></code></pre>

<h4>Note:</h4>

<p>All top level update keys which are not <code>atomic</code> operation names are treated as set operations:</p>

<h4>Example:</h4>

<pre><code><span class="keyword">var</span> query = { name: <span class="string">'borne'</span> };
Model.findOneAndUpdate(query, { name: <span class="string">'jason borne'</span> }, options, callback)

<span class="comment">// is sent as</span>
Model.findOneAndUpdate(query, { $set: { name: <span class="string">'jason borne'</span> }}, options, callback)</code></pre>

<p>This helps prevent accidentally overwriting your document with <code>{ name: 'jason borne' }</code>.</p>

<h4>Note:</h4>

<p>Although values are cast to their appropriate types when using the findAndModify helpers, the following are <em>not</em> applied:</p>

<ul>
<li>defaults</li>
<li>setters</li>
<li>validators</li>
<li>middleware</li>
</ul>

<p>If you need those features, use the traditional approach of first retrieving the document.</p>

<pre><code>Model.findOne({ name: <span class="string">'borne'</span> }, <span class="function"><span class="keyword">function</span> <span class="params">(err, doc)</span> {</span>
  <span class="keyword">if</span> (err) ..
  doc.name = <span class="string">'jason borne'</span>;
  doc.save(callback);
})</code></pre><hr class=""></div><div class="item static public"><h3 id="model_Model-findByIdAndUpdate"><a href="#model_Model-findByIdAndUpdate">Model.findByIdAndUpdate(<code>id</code>, <code>[update]</code>, <code>[options]</code>, <code>[callback]</code>)</a></h3><p>Issues a mongodb findAndModify update command by a documents id.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.findByIdAndUpdate = function (id, update, options, callback) {
  var args;

  if (1 === arguments.length) {
    if ('function' == typeof id) {
      var msg = 'Model.findByIdAndUpdate(): First argument must not be a function.

'
                + '  ' + this.modelName + '.findByIdAndUpdate(id, callback)
'
                + '  ' + this.modelName + '.findByIdAndUpdate(id)
'
                + '  ' + this.modelName + '.findByIdAndUpdate()
';
      throw new TypeError(msg)
    }
    return this.findOneAndUpdate({_id: id }, undefined);
  }

  args = utils.args(arguments, 1);
  args.unshift({ _id: id });
  return this.findOneAndUpdate.apply(this, args);
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>id</code><span class="types"> &lt;<a href="#types_objectid_ObjectId">ObjectId</a>, <a href="#HexId">HexId</a>&gt; </span><span>an ObjectId or string that can be cast to one.</span></li><li><code>[update]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[options]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[callback]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span></span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="#model_Model-findOneAndUpdate" title="Model.findOneAndUpdate">Model.findOneAndUpdate</a></li><li><a href="http://www.mongodb.org/display/DOCS/findAndModify+Command" title="mongodb">mongodb</a></li></ul></div><p>Finds a matching document, updates it according to the <code>update</code> arg, passing any <code>options</code>, and returns the found document (if any) to the callback. The query executes immediately if <code>callback</code> is passed else a Query object is returned.</p>

<h4>Options:</h4>

<ul>
<li><code>new</code>: bool - true to return the modified document rather than the original. defaults to true</li>
<li><code>upsert</code>: bool - creates the object if it doesn't exist. defaults to false.</li>
<li><code>sort</code>: if multiple docs are found by the conditions, sets the sort order to choose which doc to update</li>
<li><code>select</code>: sets the document fields to return</li>
</ul>

<h4>Examples:</h4>

<pre><code>A.findByIdAndUpdate(id, update, options, callback) <span class="comment">// executes</span>
A.findByIdAndUpdate(id, update, options)  <span class="comment">// returns Query</span>
A.findByIdAndUpdate(id, update, callback) <span class="comment">// executes</span>
A.findByIdAndUpdate(id, update)           <span class="comment">// returns Query</span>
A.findByIdAndUpdate()                     <span class="comment">// returns Query</span></code></pre>

<p>Finds a matching document, updates it according to the <code>update</code> arg, passing any <code>options</code>, and returns the found document (if any) to the callback. The query executes      immediately if <code>callback</code> is passed else a Query object is returned.</p>

<h4>Options:</h4>

<ul>
<li><code>new</code>: bool - true to return the modified document rather than the original. defaults to true</li>
<li><code>upsert</code>: bool - creates the object if it doesn't exist. defaults to false.</li>
<li><code>sort</code>: if multiple docs are found by the conditions, sets the sort order to choose which doc to update</li>
</ul>

<h4>Note:</h4>

<p>All top level update keys which are not <code>atomic</code> operation names are treated as set operations:</p>

<h4>Example:</h4>

<pre><code>Model.findByIdAndUpdate(id, { name: <span class="string">'jason borne'</span> }, options, callback)

<span class="comment">// is sent as</span>
Model.findByIdAndUpdate(id, { $set: { name: <span class="string">'jason borne'</span> }}, options, callback)</code></pre>

<p>This helps prevent accidentally overwriting your document with <code>{ name: 'jason borne' }</code>.</p>

<h4>Note:</h4>

<p>Although values are cast to their appropriate types when using the findAndModify helpers, the following are <em>not</em> applied:</p>

<ul>
<li>defaults</li>
<li>setters</li>
<li>validators</li>
<li>middleware</li>
</ul>

<p>If you need those features, use the traditional approach of first retrieving the document.</p>

<pre><code>Model.findById(id, <span class="function"><span class="keyword">function</span> <span class="params">(err, doc)</span> {</span>
  <span class="keyword">if</span> (err) ..
  doc.name = <span class="string">'jason borne'</span>;
  doc.save(callback);
})</code></pre><hr class=""></div><div class="item static public"><h3 id="model_Model-findOneAndRemove"><a href="#model_Model-findOneAndRemove">Model.findOneAndRemove(<code>conditions</code>, <code>[options]</code>, <code>[callback]</code>)</a></h3><p>Issue a mongodb findAndModify remove command.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.findOneAndRemove = function (conditions, options, callback) {
  if (1 === arguments.length &amp;&amp; 'function' == typeof conditions) {
    var msg = 'Model.findOneAndRemove(): First argument must not be a function.

'
              + '  ' + this.modelName + '.findOneAndRemove(conditions, callback)
'
              + '  ' + this.modelName + '.findOneAndRemove(conditions)
'
              + '  ' + this.modelName + '.findOneAndRemove()
';
    throw new TypeError(msg)
  }

  if ('function' == typeof options) {
    callback = options;
    options = undefined;
  }

  var fields;
  if (options) {
    fields = options.select;
    options.select = undefined;
  }

  var query = new Query(conditions);
  query.setOptions(options);
  query.select(fields);
  query.bind(this, 'findOneAndRemove');

  if ('undefined' == typeof callback)
    return query;

  this._applyNamedScope(query);
  return query.findOneAndRemove(callback);
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>conditions</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[options]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[callback]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span></span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/findAndModify+Command" title="mongodb">mongodb</a></li></ul></div><p>Finds a matching document, removes it, passing the found document (if any) to the callback.</p>

<p>Executes immediately if <code>callback</code> is passed else a Query object is returned.</p>

<h4>Options:</h4>

<ul>
<li><code>sort</code>: if multiple docs are found by the conditions, sets the sort order to choose which doc to update</li>
<li><code>select</code>: sets the document fields to return</li>
</ul>

<h4>Examples:</h4>

<pre><code>A.findOneAndRemove(conditions, options, callback) <span class="comment">// executes</span>
A.findOneAndRemove(conditions, options)  <span class="comment">// return Query</span>
A.findOneAndRemove(conditions, callback) <span class="comment">// executes</span>
A.findOneAndRemove(conditions) <span class="comment">// returns Query</span>
A.findOneAndRemove()           <span class="comment">// returns Query</span></code></pre><hr class=""></div><div class="item static public"><h3 id="model_Model-findByIdAndRemove"><a href="#model_Model-findByIdAndRemove">Model.findByIdAndRemove(<code>id</code>, <code>[options]</code>, <code>[callback]</code>)</a></h3><p>Issue a mongodb findAndModify remove command by a documents id.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.findByIdAndRemove = function (id, options, callback) {
  if (1 === arguments.length &amp;&amp; 'function' == typeof id) {
    var msg = 'Model.findByIdAndRemove(): First argument must not be a function.

'
              + '  ' + this.modelName + '.findByIdAndRemove(id, callback)
'
              + '  ' + this.modelName + '.findByIdAndRemove(id)
'
              + '  ' + this.modelName + '.findByIdAndRemove()
';
    throw new TypeError(msg)
  }

  return this.findOneAndRemove({ _id: id }, options, callback);
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>id</code><span class="types"> &lt;<a href="#types_objectid_ObjectId">ObjectId</a>, <a href="#HexString">HexString</a>&gt; </span><span>ObjectId or string that can be cast to one</span></li><li><code>[options]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[callback]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span></span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="#model_Model-findOneAndRemove" title="Model.findOneAndRemove">Model.findOneAndRemove</a></li><li><a href="http://www.mongodb.org/display/DOCS/findAndModify+Command" title="mongodb">mongodb</a></li></ul></div><p>Finds a matching document, removes it, passing the found document (if any) to the callback.</p>

<p>Executes immediately if <code>callback</code> is passed, else a <code>Query</code> object is returned.</p>

<h4>Options:</h4>

<ul>
<li><code>sort</code>: if multiple docs are found by the conditions, sets the sort order to choose which doc to update</li>
<li><code>select</code>: sets the document fields to return</li>
</ul>

<h4>Examples:</h4>

<pre><code>A.findByIdAndRemove(id, options, callback) <span class="comment">// executes</span>
A.findByIdAndRemove(id, options)  <span class="comment">// return Query</span>
A.findByIdAndRemove(id, callback) <span class="comment">// executes</span>
A.findByIdAndRemove(id) <span class="comment">// returns Query</span>
A.findByIdAndRemove()           <span class="comment">// returns Query</span></code></pre><hr class=""></div><div class="item static public"><h3 id="model_Model-create"><a href="#model_Model-create">Model.create(<code>doc</code>, <code>fn</code>)</a></h3><p>Shortcut for creating a new Document that is automatically saved to the db if valid.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.create = <span class="function"><span class="keyword">function</span> <span class="title">create</span> <span class="params">(doc, fn)</span> {</span>
  <span class="keyword">if</span> (<span class="number">1</span> === arguments.length) {
    <span class="keyword">return</span> <span class="string">'function'</span> === <span class="keyword">typeof</span> doc &amp;&amp; doc(<span class="literal">null</span>);
  }

  <span class="keyword">var</span> self = <span class="keyword">this</span>
    , docs = [<span class="literal">null</span>]
    , promise
    , count
    , args

  <span class="keyword">if</span> (Array.isArray(doc)) {
    args = doc;
  } <span class="keyword">else</span> {
    args = utils.args(arguments, <span class="number">0</span>, arguments.length - <span class="number">1</span>);
    fn = arguments[arguments.length - <span class="number">1</span>];
  }

  <span class="keyword">if</span> (<span class="number">0</span> === args.length) <span class="keyword">return</span> fn(<span class="literal">null</span>);

  promise = <span class="keyword">new</span> Promise(fn);
  count = args.length;

  args.forEach(<span class="function"><span class="keyword">function</span> <span class="params">(arg, i)</span> {</span>
    <span class="keyword">var</span> doc = <span class="keyword">new</span> self(arg);
    docs[i+<span class="number">1</span>] = doc;
    doc.save(<span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
      <span class="keyword">if</span> (err) <span class="keyword">return</span> promise.error(err);
      --count || fn.apply(<span class="literal">null</span>, docs);
    });
  });

  <span class="comment">// TODO</span>
  <span class="comment">// utilize collection.insertAll for batch processing?</span>
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>doc</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array">Array</a>, <a href="#Object...">Object...</a>&gt; </span><span></span></li><li><code>fn</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span>callback</span></li></ul></div><h4>Example:</h4>

<pre><code>Candy.create({ type: <span class="string">'jelly bean'</span> }, { type: <span class="string">'snickers'</span> }, <span class="function"><span class="keyword">function</span> <span class="params">(err, jellybean, snickers)</span> {</span>
  <span class="keyword">if</span> (err) <span class="comment">// ...</span>
});

<span class="keyword">var</span> array = [{ type: <span class="string">'jelly bean'</span> }, { type: <span class="string">'snickers'</span> }];
Candy.create(array, <span class="function"><span class="keyword">function</span> <span class="params">(err, jellybean, snickers)</span> {</span>
  <span class="keyword">if</span> (err) <span class="comment">// ...</span>
});</code></pre><hr class=""></div><div class="item static public"><h3 id="model_Model-update"><a href="#model_Model-update">Model.update(<code>conditions</code>, <code>update</code>, <code>[options]</code>, <code>[callback]</code>)</a></h3><p>Updates documents in the database without returning them.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.update = <span class="function"><span class="keyword">function</span> <span class="title">update</span> <span class="params">(conditions, doc, options, callback)</span> {</span>
  <span class="keyword">if</span> (arguments.length &lt; <span class="number">4</span>) {
    <span class="keyword">if</span> (<span class="string">'function'</span> === <span class="keyword">typeof</span> options) {
      <span class="comment">// Scenario: update(conditions, doc, callback)</span>
      callback = options;
      options = <span class="literal">null</span>;
    } <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">'function'</span> === <span class="keyword">typeof</span> doc) {
      <span class="comment">// Scenario: update(doc, callback);</span>
      callback = doc;
      doc = conditions;
      conditions = {};
      options = <span class="literal">null</span>;
    }
  }

  <span class="keyword">var</span> query = <span class="keyword">new</span> Query(conditions, options).bind(<span class="keyword">this</span>, <span class="string">'update'</span>, doc);

  <span class="keyword">if</span> (<span class="string">'undefined'</span> == <span class="keyword">typeof</span> callback)
    <span class="keyword">return</span> query;

  <span class="keyword">this</span>._applyNamedScope(query);
  <span class="keyword">return</span> query.update(doc, callback);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>conditions</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>update</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[options]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[callback]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span></span></li></ul></div><h4>Examples:</h4>

<pre><code>MyModel.update({ age: { $gt: <span class="number">18</span> } }, { oldEnough: <span class="literal">true</span> }, fn);
MyModel.update({ name: <span class="string">'Tobi'</span> }, { ferret: <span class="literal">true</span> }, { multi: <span class="literal">true</span> }, <span class="function"><span class="keyword">function</span> <span class="params">(err, numberAffected, raw)</span> {</span>
  <span class="keyword">if</span> (err) <span class="keyword">return</span> handleError(err);
  console.log(<span class="string">'The number of updated documents was %d'</span>, numberAffected);
  console.log(<span class="string">'The raw response from Mongo was '</span>, raw);
});</code></pre>

<h4>Valid options:</h4>

<ul>
<li><code>safe</code> (boolean) safe mode (defaults to value set in schema (true))</li>
<li><code>upsert</code> (boolean) whether to create the doc if it doesn't match (false)</li>
<li><code>multi</code> (boolean) whether multiple documents should be updated (false)</li>
</ul>

<p>All <code>update</code> values are cast to their appropriate SchemaTypes before being sent.</p>

<p>The <code>callback</code> function receives <code>(err, numberAffected, rawResponse)</code>.</p>

<ul>
<li><code>err</code> is the error if any occurred</li>
<li><code>numberAffected</code> is the count of updated documents Mongo reported</li>
<li><code>rawResponse</code> is the full response from Mongo</li>
</ul>

<h4>Note:</h4>

<p>All top level keys which are not <code>atomic</code> operation names are treated as set operations:</p>

<h4>Example:</h4>

<pre><code><span class="keyword">var</span> query = { name: <span class="string">'borne'</span> };
Model.update(query, { name: <span class="string">'jason borne'</span> }, options, callback)

<span class="comment">// is sent as</span>
Model.update(query, { $set: { name: <span class="string">'jason borne'</span> }}, options, callback)</code></pre>

<p>This helps prevent accidentally overwriting all documents in your collection with <code>{ name: 'jason borne' }</code>.</p>

<h4>Note:</h4>

<p>To update documents without waiting for a response from MongoDB, do not pass a <code>callback</code>, then call <code>exec</code> on the returned <a href="#query-js">Query</a>:</p>

<pre><code>Comment.update({ _id: id }, { $set: { text: <span class="string">'changed'</span> }}).exec();</code></pre>

<h4>Note:</h4>

<p>Although values are casted to their appropriate types when using update, the following are <em>not</em> applied:</p>

<ul>
<li>defaults</li>
<li>setters</li>
<li>validators</li>
<li>middleware</li>
</ul>

<p>If you need those features, use the traditional approach of first retrieving the document.</p>

<pre><code>Model.findOne({ name: <span class="string">'borne'</span> }, <span class="function"><span class="keyword">function</span> <span class="params">(err, doc)</span> {</span>
  <span class="keyword">if</span> (err) ..
  doc.name = <span class="string">'jason borne'</span>;
  doc.save(callback);
})</code></pre><hr class=""></div><div class="item static public"><h3 id="model_Model-mapReduce"><a href="#model_Model-mapReduce">Model.mapReduce(<code>o</code>, <code>callback</code>)</a></h3><p>Executes a mapReduce command.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.mapReduce = <span class="function"><span class="keyword">function</span> <span class="title">mapReduce</span> <span class="params">(o, callback)</span> {</span>
  <span class="keyword">if</span> (<span class="string">'function'</span> != <span class="keyword">typeof</span> callback) <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">'missing callback'</span>);

  <span class="keyword">var</span> self = <span class="keyword">this</span>;

  <span class="keyword">if</span> (!Model.mapReduce.schema) {
    <span class="keyword">var</span> opts = { noId: <span class="literal">true</span>, noVirtualId: <span class="literal">true</span>, strict: <span class="literal">false</span> }
    Model.mapReduce.schema = <span class="keyword">new</span> Schema({}, opts);
  }

  <span class="keyword">if</span> (!o.out) o.out = { inline: <span class="number">1</span> };

  o.map = String(o.map);
  o.reduce = String(o.reduce);

  <span class="keyword">if</span> (o.query) {
    <span class="keyword">var</span> q = <span class="keyword">new</span> Query(o.query);
    q.cast(<span class="keyword">this</span>);
    o.query = q._conditions;
    q = <span class="literal">undefined</span>;
  }

  <span class="keyword">this</span>.collection.mapReduce(<span class="literal">null</span>, <span class="literal">null</span>, o, <span class="function"><span class="keyword">function</span> <span class="params">(err, ret, stats)</span> {</span>
    <span class="keyword">if</span> (err) <span class="keyword">return</span> callback(err);

    <span class="keyword">if</span> (ret.findOne &amp;&amp; ret.mapReduce) {
      <span class="comment">// returned a collection, convert to Model</span>
      <span class="keyword">var</span> model = Model.compile(
          <span class="string">'_mapreduce_'</span> + ret.collectionName
        , Model.mapReduce.schema
        , ret.collectionName
        , self.db
        , self.base);

      model._mapreduce = <span class="literal">true</span>;

      <span class="keyword">return</span> callback(err, model, stats);
    }

    callback(err, ret, stats);
  });
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>o</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>an object specifying map-reduce options</span></li><li><code>callback</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/MapReduce">http://www.mongodb.org/display/DOCS/MapReduce</a></li></ul></div><p><code>o</code> is an object specifying all mapReduce options as well as the map and reduce functions. All options are delegated to the driver implementation.</p>

<h4>Example:</h4>

<pre><code><span class="keyword">var</span> o = {};
o.map = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span> emit(<span class="keyword">this</span>.name, <span class="number">1</span>) }
o.reduce = <span class="function"><span class="keyword">function</span> <span class="params">(k, vals)</span> {</span> <span class="keyword">return</span> vals.length }
User.mapReduce(o, <span class="function"><span class="keyword">function</span> <span class="params">(err, results)</span> {</span>
  console.log(results)
})</code></pre>

<h4>Other options:</h4>

<ul>
<li><code>query</code> {Object} query filter object.</li>
<li><code>limit</code> {Number} max number of documents</li>
<li><code>keeptemp</code> {Boolean, default:false} keep temporary data</li>
<li><code>finalize</code> {Function} finalize function</li>
<li><code>scope</code> {Object} scope variables exposed to map/reduce/finalize during execution</li>
<li><code>jsMode</code> {Boolean, default:false} it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X</li>
<li><code>verbose</code> {Boolean, default:false} provide statistics on job execution time.</li>
<li><code>out*</code> {Object, default: {inline:1}} sets the output target for the map reduce job.</li>
</ul>

<h4>* out options:</h4>

<ul>
<li><code>{inline:1}</code> the results are returned in an array</li>
<li><code>{replace: 'collectionName'}</code> add the results to collectionName: the results replace the collection</li>
<li><code>{reduce: 'collectionName'}</code> add the results to collectionName: if dups are detected, uses the reducer / finalize functions</li>
<li><code>{merge: 'collectionName'}</code> add the results to collectionName: if dups exist the new docs overwrite the old</li>
</ul>

<p>If <code>options.out</code> is set to <code>replace</code>, <code>merge</code>, or <code>reduce</code>, a Model instance is returned that can be used for further querying. Queries run against this model are all executed with the <code>lean</code> option; meaning only the js object is returned and no Mongoose magic is applied (getters, setters, etc).</p>

<h4>Example:</h4>

<pre><code><span class="keyword">var</span> o = {};
o.map = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span> emit(<span class="keyword">this</span>.name, <span class="number">1</span>) }
o.reduce = <span class="function"><span class="keyword">function</span> <span class="params">(k, vals)</span> {</span> <span class="keyword">return</span> vals.length }
o.out = { replace: <span class="string">'createdCollectionNameForResults'</span> }
o.verbose = <span class="literal">true</span>;
User.mapReduce(o, <span class="function"><span class="keyword">function</span> <span class="params">(err, model, stats)</span> {</span>
  console.log(<span class="string">'map reduce took %d ms'</span>, stats.processtime)
  model.find().where(<span class="string">'value'</span>).gt(<span class="number">10</span>).exec(<span class="function"><span class="keyword">function</span> <span class="params">(err, docs)</span> {</span>
    console.log(docs);
  });
})</code></pre><hr class=""></div><div class="item static public"><h3 id="model_Model-aggregate"><a href="#model_Model-aggregate">Model.aggregate(<code>array</code>, <code>[options]</code>, <code>callback</code>)</a></h3><p>Executes an aggregate command on this models collection.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Model.aggregate = <span class="function"><span class="keyword">function</span> <span class="title">aggregate</span> <span class="params">()</span> {</span>
  <span class="keyword">return</span> <span class="keyword">this</span>.collection.aggregate.apply(<span class="keyword">this</span>.collection, arguments);
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>array</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array">Array</a>&gt; </span><span>an array of pipeline commands</span></li><li><code>[options]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>callback</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://docs.mongodb.org/manual/applications/aggregation/" title="aggregation">aggregation</a></li><li><a href="http://mongodb.github.com/node-mongodb-native/api-generated/collection.html#aggregate" title="driver">driver</a></li></ul></div><h4>Example:</h4>

<pre><code><span class="comment">// find the max age of all users</span>
Users.aggregate(
    { $group: { _id: <span class="literal">null</span>, maxAge: { $max: <span class="string">'$age'</span> }}}
  , { $project: { _id: <span class="number">0</span>, maxAge: <span class="number">1</span> }}
  , <span class="function"><span class="keyword">function</span> <span class="params">(err, res)</span> {</span>
  <span class="keyword">if</span> (err) <span class="keyword">return</span> handleError(err);
  console.log(res); <span class="comment">// [ { maxAge: 98 } ]</span>
});</code></pre>

<p><em>NOTE: the documents returned are plain javascript objects, not mongoose documents cast to this models schema definition (since any shape of document can be returned).</em></p>

<p><em>NOTE: this requires running MongoDB >= 2.1</em></p><hr class=""></div><div class="item property public"><h3 id="model_Model-base"><a href="#model_Model-base">Model#<span>base</span></a></h3><p>Base Mongoose instance the model uses.</p><hr class=""></div><div class="item property public"><h3 id="model_Model-collection"><a href="#model_Model-collection">Model#<span>collection</span></a></h3><p>Collection the model uses.</p><hr class=""></div><div class="item property public"><h3 id="model_Model-db"><a href="#model_Model-db">Model#<span>db</span></a></h3><p>Database instance the model uses.</p><hr class=""></div><div class="item property public"><h3 id="model_Model-schema"><a href="#model_Model-schema">Model#<span>schema</span></a></h3><p>Schema the model uses.</p><hr class=""></div><div class="item property public"><h3 id="model_Model-modelName"><a href="#model_Model-modelName">Model#<span>modelName</span></a></h3><p>The name of the model</p><hr class=""></div><div class="item property public"><h3 id="model_Model-collection"><a href="#model_Model-collection">Model#<span>collection</span></a></h3><p>Collection the model uses.</p><hr class=""></div><div class="item property public"><h3 id="model_Model-db"><a href="#model_Model-db">Model#<span>db</span></a></h3><p>Connection the model uses.</p><hr class=""></div></li><li class="module private"><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/namedscope.js" id="namedscope-js">namedscope.js</a><div class="item method private"><h3 id="namedscope_NamedScope-decorate"><a href="#namedscope_NamedScope-decorate">NamedScope#decorate(<code>target</code>, <code>getters</code>)</a></h3><p>Decorate</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">NamedScope.prototype.decorate = <span class="function"><span class="keyword">function</span> <span class="params">(target, getters)</span> {</span>
  <span class="keyword">var</span> name = <span class="keyword">this</span>.name
    , block = <span class="keyword">this</span>.block
    , query = <span class="keyword">this</span>.query;
  <span class="keyword">if</span> (block) {
    <span class="keyword">if</span> (block.length === <span class="number">0</span>) {
      Object.defineProperty(target, name, {
        get: getters.block0(block)
      });
    } <span class="keyword">else</span> {
      target[name] = getters.blockN(block);
    }
  } <span class="keyword">else</span> {
    Object.defineProperty(target, name, {
      get: getters.basic(query)
    });
  }
};

NamedScope.prototype.compile = <span class="function"><span class="keyword">function</span> <span class="params">(model)</span> {</span>
  <span class="keyword">var</span> allScopes = <span class="keyword">this</span>.scopesByName
    , scope;
  <span class="keyword">for</span> (<span class="keyword">var</span> k <span class="keyword">in</span> allScopes) {
    scope = allScopes[k];
    scope.decorate(model, {
      block0: <span class="function"><span class="keyword">function</span> <span class="params">(block)</span> {</span>
        <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
          <span class="keyword">var</span> cquery = <span class="keyword">this</span>._cumulativeQuery || (<span class="keyword">this</span>._cumulativeQuery = <span class="keyword">new</span> Query().bind(<span class="keyword">this</span>));
          block.call(cquery);
          <span class="keyword">return</span> <span class="keyword">this</span>;
        };
      },
      blockN: <span class="function"><span class="keyword">function</span> <span class="params">(block)</span> {</span>
        <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
          <span class="keyword">var</span> cquery = <span class="keyword">this</span>._cumulativeQuery || (<span class="keyword">this</span>._cumulativeQuery = <span class="keyword">new</span> Query().bind(<span class="keyword">this</span>));
          block.apply(cquery, arguments);
          <span class="keyword">return</span> <span class="keyword">this</span>;
        };
      },
      basic: <span class="function"><span class="keyword">function</span> <span class="params">(query)</span> {</span>
        <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
          <span class="keyword">var</span> cquery = <span class="keyword">this</span>._cumulativeQuery || (<span class="keyword">this</span>._cumulativeQuery = <span class="keyword">new</span> Query().bind(<span class="keyword">this</span>));
          cquery.find(query);
          <span class="keyword">return</span> <span class="keyword">this</span>;
        };
      }
    });
  }
};

module.exports = NamedScope;</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>target</code><span class="types"> &lt;<a href="#NamedScope">NamedScope</a>&gt; </span><span></span></li><li><code>getters</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div></li><li class="module "><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/promise.js" id="promise-js">promise.js</a><div class="item method public"><h3 id="promise_Promise"><a href="#promise_Promise">Promise(<code>back</code>)</a></h3><p>Promise constructor.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">Promise</span> <span class="params">(back)</span> {</span>
  <span class="keyword">this</span>.emitted = {};
  <span class="keyword">if</span> (<span class="string">'function'</span> == <span class="keyword">typeof</span> back)
    <span class="keyword">this</span>.addBack(back);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>back</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span>a callback+errback that accepts `fn(err, ...){}` as signature</span></li></ul></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="http://nodejs.org/api/events.html#events_class_events_eventemitter" title="NodeJS EventEmitter">NodeJS EventEmitter</a></li></ul></div><div class="events"><h4>Events:</h4><ul><li><p><code>err</code>: Emits when the promise resolves to an error.</p></li><li><p><code>complete</code>: Emits when the promise resolves sucessfully.</p></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="promise_Promise-on"><a href="#promise_Promise-on">Promise#on(<code>event</code>, <code>callback</code>)</a></h3><p>Adds <code>listener</code> to the <code>event</code>.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Promise.prototype.on = <span class="function"><span class="keyword">function</span> <span class="params">(event, callback)</span> {</span>
  <span class="keyword">if</span> (<span class="keyword">this</span>.emitted[event])
    callback.apply(<span class="keyword">this</span>, <span class="keyword">this</span>.emitted[event]);
  <span class="keyword">else</span>
    EventEmitter.prototype.on.call(<span class="keyword">this</span>, event, callback);

  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>event</code><span class="types"> &lt;<a href="#Event">Event</a>&gt; </span><span></span></li><li><code>callback</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#promise_Promise">Promise</a>&gt; </span><span>this</span></li></ul></div><div class="description"><p>If <code>event</code> is either <code>error</code> or <code>complete</code> and the event has already been emitted, the<code>listener</code> is called immediately and passed the results of the original emitted event.</p></div><hr class=""></div><div class="item method private"><h3 id="promise_Promise-emit"><a href="#promise_Promise-emit">Promise#emit()</a></h3><p>Keeps track of emitted events to run them on <code>on</code>.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Promise.prototype.emit = <span class="function"><span class="keyword">function</span> <span class="params">(event)</span> {</span>
  <span class="comment">// ensures a promise can't be complete() or error() twice</span>
  <span class="keyword">if</span> (event == <span class="string">'err'</span> || event == <span class="string">'complete'</span>){
    <span class="keyword">if</span> (<span class="keyword">this</span>.emitted.err || <span class="keyword">this</span>.emitted.complete) {
      <span class="keyword">return</span> <span class="keyword">this</span>;
    }
    <span class="keyword">this</span>.emitted[event] = util.args(arguments, <span class="number">1</span>);
  }

  <span class="keyword">return</span> EventEmitter.prototype.emit.apply(<span class="keyword">this</span>, arguments);
};</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="promise_Promise-complete"><a href="#promise_Promise-complete">Promise#complete()</a></h3><p>Shortcut for emitting the <code>complete</code> event.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Promise.prototype.complete = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">var</span> args = util.args(arguments);
  <span class="keyword">return</span> <span class="keyword">this</span>.emit.apply(<span class="keyword">this</span>, [<span class="string">'complete'</span>].concat(args));
};</code></pre></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="promise_Promise-error"><a href="#promise_Promise-error">Promise#error()</a></h3><p>Shortcut for emitting the <code>err</code> event.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Promise.prototype.error = <span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
  <span class="keyword">if</span> (!(err <span class="keyword">instanceof</span> Error)) err = <span class="keyword">new</span> Error(err);
  <span class="keyword">return</span> <span class="keyword">this</span>.emit(<span class="string">'err'</span>, err);
};</code></pre></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#promise_Promise">Promise</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="promise_Promise-addCallback"><a href="#promise_Promise-addCallback">Promise#addCallback()</a></h3><p>Shortcut for <code>.on('complete', fn)</code>.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Promise.prototype.addCallback = <span class="function"><span class="keyword">function</span> <span class="params">(fn)</span> {</span>
  <span class="keyword">return</span> <span class="keyword">this</span>.on(<span class="string">'complete'</span>, fn);
};</code></pre></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#promise_Promise">Promise</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="promise_Promise-addErrback"><a href="#promise_Promise-addErrback">Promise#addErrback()</a></h3><p>Shortcut for <code>.on('err', fn)</code>.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Promise.prototype.addErrback = <span class="function"><span class="keyword">function</span> <span class="params">(fn)</span> {</span>
  <span class="keyword">return</span> <span class="keyword">this</span>.on(<span class="string">'err'</span>, fn);
};</code></pre></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#promise_Promise">Promise</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="promise_Promise-addBack"><a href="#promise_Promise-addBack">Promise#addBack(<code>fn</code>)</a></h3><p>Adds a single function that's both a callback and errback.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Promise.prototype.addBack = <span class="function"><span class="keyword">function</span> <span class="params">(fn)</span> {</span>
  <span class="keyword">this</span>.on(<span class="string">'err'</span>, <span class="keyword">function</span>(err){
    fn.call(<span class="keyword">this</span>, err);
  });

  <span class="keyword">this</span>.on(<span class="string">'complete'</span>, <span class="keyword">function</span>(){
    <span class="keyword">var</span> args = util.args(arguments);
    fn.apply(<span class="keyword">this</span>, [<span class="literal">null</span>].concat(args));
  });

  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>fn</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#promise_Promise">Promise</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="promise_Promise-resolve"><a href="#promise_Promise-resolve">Promise#resolve(<code>err</code>, <code>val</code>)</a></h3><p>Sugar for handling cases where you may be resolving to either an error condition or a success condition.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Promise.prototype.resolve = <span class="function"><span class="keyword">function</span> <span class="params">(err, val)</span> {</span>
  <span class="keyword">if</span> (err) <span class="keyword">return</span> <span class="keyword">this</span>.error(err);
  <span class="keyword">return</span> <span class="keyword">this</span>.complete(val);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>err</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error">Error</a>&gt; </span><span>optional error or null</span></li><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>value to complete the promise with</span></li></ul></div><div class="description"></div><hr class=""></div></li><li class="module "><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/query.js" id="query-js">query.js</a><div class="item method public"><h3 id="query_Query"><a href="#query_Query">Query(<code>criteria</code>, <code>options</code>)</a></h3><p>Query constructor used for building queries.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">Query</span> <span class="params">(criteria, options)</span> {</span>
  <span class="keyword">this</span>.setOptions(options, <span class="literal">true</span>);
  <span class="keyword">this</span>._conditions = {};
  <span class="keyword">this</span>._updateArg = {};
  <span class="keyword">this</span>._fields = <span class="literal">undefined</span>;
  <span class="keyword">if</span> (criteria) <span class="keyword">this</span>.find(criteria);
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>criteria</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>options</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code><span class="keyword">var</span> query = Model.find();
query.where(<span class="string">'age'</span>).gte(<span class="number">21</span>).exec(callback);</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-setOptions"><a href="#query_Query-setOptions">Query#setOptions(<code>options</code>)</a></h3><p>Sets query options.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.setOptions = <span class="function"><span class="keyword">function</span> <span class="params">(options, overwrite)</span> {</span>
  <span class="comment">// overwrite is internal use only</span>
  <span class="keyword">if</span> (overwrite) {
    options = <span class="keyword">this</span>.options = options || {};
    <span class="keyword">this</span>.safe = options.safe

    <span class="comment">// normalize population options</span>
    <span class="keyword">var</span> pop = <span class="keyword">this</span>.options.populate;
    <span class="keyword">this</span>.options.populate = {};

    <span class="keyword">if</span> (pop &amp;&amp; Array.isArray(pop)) {
      <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>, l = pop.length; i &lt; l; i++) {
        <span class="keyword">this</span>.options.populate[pop[i]] = {};
      }
    }

    <span class="keyword">return</span> <span class="keyword">this</span>;
  }

  <span class="keyword">if</span> (!(options &amp;&amp; <span class="string">'Object'</span> == options.constructor.name))
    <span class="keyword">return</span> <span class="keyword">this</span>;

  <span class="keyword">if</span> (<span class="string">'safe'</span> <span class="keyword">in</span> options)
    <span class="keyword">this</span>.safe = options.safe;

  <span class="comment">// set arbitrary options</span>
  <span class="keyword">var</span> methods = Object.keys(options)
    , i = methods.length
    , method

  <span class="keyword">while</span> (i--) {
    method = methods[i];

    <span class="comment">// use methods if exist (safer option manipulation)</span>
    <span class="keyword">if</span> (<span class="string">'function'</span> == <span class="keyword">typeof</span> <span class="keyword">this</span>[method]) {
      <span class="keyword">var</span> args = Array.isArray(options[method])
        ? options[method]
        : [options[method]];
      <span class="keyword">this</span>[method].apply(<span class="keyword">this</span>, args)
    } <span class="keyword">else</span> {
      <span class="keyword">this</span>.options[method] = options[method];
    }
  }
  <span class="keyword">return</span> <span class="keyword">this</span>;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>options</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="description"><h4>Options:</h4>

<ul>
<li><a href="http://www.mongodb.org/display/DOCS/Tailable+Cursors">tailable</a> *</li>
<li><a href="http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsort()%7D%7D">sort</a> *</li>
<li><a href="http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D">limit</a> *</li>
<li><a href="http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D">skip</a> *</li>
<li><a href="http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan">maxscan</a> *</li>
<li><a href="http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D">batchSize</a> *</li>
<li><a href="http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment">comment</a> *</li>
<li><a href="http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D">snapshot</a> *</li>
<li><a href="http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint">hint</a> *</li>
<li><a href="http://docs.mongodb.org/manual/applications/replication/#read-preference">slaveOk</a> *</li>
<li><a href="./api.html#query_Query-lean">lean</a> *</li>
<li><a href="http://www.mongodb.org/display/DOCS/getLastError+Command">safe</a></li>
</ul>

<p><em>* denotes a query helper method is also available</em></p></div><hr class=""></div><div class="item method private"><h3 id="query_Query-bind"><a href="#query_Query-bind">Query#bind(<code>model</code>, <code>op</code>, <code>updateArg</code>)</a></h3><p>Binds this query to a model.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.bind = <span class="function"><span class="keyword">function</span> <span class="title">bind</span> <span class="params">(model, op, updateArg)</span> {</span>
  <span class="keyword">this</span>.model = model;
  <span class="keyword">this</span>.op = op;

  <span class="keyword">if</span> (model._mapreduce) <span class="keyword">this</span>.options.lean = <span class="literal">true</span>;

  <span class="keyword">if</span> (op == <span class="string">'update'</span> || op == <span class="string">'findOneAndUpdate'</span>) {
    merge(<span class="keyword">this</span>._updateArg, updateArg || {});
  }

  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>model</code><span class="types"> &lt;<a href="#model_Model">Model</a>&gt; </span><span>the model to which the query is bound</span></li><li><code>op</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>the operation to execute</span></li><li><code>updateArg</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>used in update methods</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="query_Query-exec"><a href="#query_Query-exec">Query#exec(<code>[operation]</code>, <code>[callback]</code>)</a></h3><p>Executes the query</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.exec = <span class="function"><span class="keyword">function</span> <span class="title">exec</span> <span class="params">(op, callback)</span> {</span>
  <span class="keyword">var</span> promise = <span class="keyword">new</span> Promise();

  <span class="keyword">switch</span> (<span class="keyword">typeof</span> op) {
    <span class="keyword">case</span> <span class="string">'function'</span>:
      callback = op;
      op = <span class="literal">null</span>;
      <span class="keyword">break</span>;
    <span class="keyword">case</span> <span class="string">'string'</span>:
      <span class="keyword">this</span>.op = op;
      <span class="keyword">break</span>;
  }

  <span class="keyword">if</span> (callback) promise.addBack(callback);

  <span class="keyword">if</span> (!<span class="keyword">this</span>.op) {
    promise.complete();
    <span class="keyword">return</span> promise;
  }

  <span class="keyword">if</span> (<span class="string">'update'</span> == <span class="keyword">this</span>.op) {
    <span class="keyword">this</span>[<span class="keyword">this</span>.op](<span class="keyword">this</span>._updateArg, promise.resolve.bind(promise));
    <span class="keyword">return</span> promise;
  }

  <span class="keyword">if</span> (<span class="string">'distinct'</span> == <span class="keyword">this</span>.op) {
    <span class="keyword">this</span>.distinct(<span class="keyword">this</span>._distinctArg, promise.resolve.bind(promise));
    <span class="keyword">return</span> promise;
  }

  <span class="keyword">this</span>[<span class="keyword">this</span>.op](promise.resolve.bind(promise));
  <span class="keyword">return</span> promise;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>[operation]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li><li><code>[callback]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#promise_Promise">Promise</a>&gt; </span><span></span></li></ul></div><div class="description"><h4>Examples</h4>

<pre><code>query.exec();
query.exec(callback);
query.exec(<span class="string">'update'</span>);
query.exec(<span class="string">'find'</span>, callback);</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-find"><a href="#query_Query-find">Query#find(<code>[criteria]</code>, <code>[callback]</code>)</a></h3><p>Finds documents.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.find = <span class="function"><span class="keyword">function</span> <span class="params">(criteria, callback)</span> {</span>
  <span class="keyword">this</span>.op = <span class="string">'find'</span>;
  <span class="keyword">if</span> (<span class="string">'function'</span> === <span class="keyword">typeof</span> criteria) {
    callback = criteria;
    criteria = {};
  } <span class="keyword">else</span> <span class="keyword">if</span> (criteria <span class="keyword">instanceof</span> Query) {
    <span class="comment">// TODO Merge options, too</span>
    merge(<span class="keyword">this</span>._conditions, criteria._conditions);
  } <span class="keyword">else</span> <span class="keyword">if</span> (criteria <span class="keyword">instanceof</span> Document) {
    merge(<span class="keyword">this</span>._conditions, criteria.toObject());
  } <span class="keyword">else</span> <span class="keyword">if</span> (criteria &amp;&amp; <span class="string">'Object'</span> === criteria.constructor.name) {
    merge(<span class="keyword">this</span>._conditions, criteria);
  }
  <span class="keyword">if</span> (!callback) <span class="keyword">return</span> <span class="keyword">this</span>;
  <span class="keyword">return</span> <span class="keyword">this</span>.execFind(callback);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>[criteria]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>mongodb selector</span></li><li><code>[callback]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="description"><p>When no <code>callback</code> is passed, the query is not executed.</p>

<h4>Example</h4>

<pre><code>query.find({ name: <span class="string">'Los Pollos Hermanos'</span> }).find(callback)</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-cast"><a href="#query_Query-cast">Query#cast(<code>model</code>, <code>[obj]</code>)</a></h3><p>Casts this query to the schema of <code>model</code></p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.cast = <span class="function"><span class="keyword">function</span> <span class="params">(model, obj)</span> {</span>
  obj || (obj= <span class="keyword">this</span>._conditions);

  <span class="keyword">var</span> schema = model.schema
    , paths = Object.keys(obj)
    , i = paths.length
    , any$conditionals
    , schematype
    , nested
    , path
    , type
    , val;

  <span class="keyword">while</span> (i--) {
    path = paths[i];
    val = obj[path];

    <span class="keyword">if</span> (<span class="string">'$or'</span> === path || <span class="string">'$nor'</span> === path) {
      <span class="keyword">var</span> k = val.length
        , orComponentQuery;

      <span class="keyword">while</span> (k--) {
        orComponentQuery = <span class="keyword">new</span> Query(val[k]);
        orComponentQuery.cast(model);
        val[k] = orComponentQuery._conditions;
      }

    } <span class="keyword">else</span> <span class="keyword">if</span> (path === <span class="string">'$where'</span>) {
      type = <span class="keyword">typeof</span> val;

      <span class="keyword">if</span> (<span class="string">'string'</span> !== type &amp;&amp; <span class="string">'function'</span> !== type) {
        <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">"Must have a string or function for $where"</span>);
      }

      <span class="keyword">if</span> (<span class="string">'function'</span> === type) {
        obj[path] = val.toString();
      }

      <span class="keyword">continue</span>;

    } <span class="keyword">else</span> {

      <span class="keyword">if</span> (!schema) {
        <span class="comment">// no casting for Mixed types</span>
        <span class="keyword">continue</span>;
      }

      schematype = schema.path(path);

      <span class="keyword">if</span> (!schematype) {
        <span class="comment">// Handle potential embedded array queries</span>
        <span class="keyword">var</span> split = path.split(<span class="string">'.'</span>)
          , j = split.length
          , pathFirstHalf
          , pathLastHalf
          , remainingConds
          , castingQuery;

        <span class="comment">// Find the part of the var path that is a path of the Schema</span>
        <span class="keyword">while</span> (j--) {
          pathFirstHalf = split.slice(<span class="number">0</span>, j).join(<span class="string">'.'</span>);
          schematype = schema.path(pathFirstHalf);
          <span class="keyword">if</span> (schematype) <span class="keyword">break</span>;
        }

        <span class="comment">// If a substring of the input path resolves to an actual real path...</span>
        <span class="keyword">if</span> (schematype) {
          <span class="comment">// Apply the casting; similar code for $elemMatch in schema/array.js</span>
          <span class="keyword">if</span> (schematype.caster &amp;&amp; schematype.caster.schema) {
            remainingConds = {};
            pathLastHalf = split.slice(j).join(<span class="string">'.'</span>);
            remainingConds[pathLastHalf] = val;
            castingQuery = <span class="keyword">new</span> Query(remainingConds);
            castingQuery.cast(schematype.caster);
            obj[path] = castingQuery._conditions[pathLastHalf];
          } <span class="keyword">else</span> {
            obj[path] = val;
          }
        }

      } <span class="keyword">else</span> <span class="keyword">if</span> (val === <span class="literal">null</span> || val === <span class="literal">undefined</span>) {
        <span class="keyword">continue</span>;
      } <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">'Object'</span> === val.constructor.name) {

        any$conditionals = Object.keys(val).some(<span class="function"><span class="keyword">function</span> <span class="params">(k)</span> {</span>
          <span class="keyword">return</span> k.charAt(<span class="number">0</span>) === <span class="string">'$'</span> &amp;&amp; k !== <span class="string">'$id'</span> &amp;&amp; k !== <span class="string">'$ref'</span>;
        });

        <span class="keyword">if</span> (!any$conditionals) {
          obj[path] = schematype.castForQuery(val);
        } <span class="keyword">else</span> {

          <span class="keyword">var</span> ks = Object.keys(val)
            , k = ks.length
            , $cond;

          <span class="keyword">while</span> (k--) {
            $cond = ks[k];
            nested = val[$cond];

            <span class="keyword">if</span> (<span class="string">'$exists'</span> === $cond) {
              <span class="keyword">if</span> (<span class="string">'boolean'</span> !== <span class="keyword">typeof</span> nested) {
                <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">"$exists parameter must be Boolean"</span>);
              }
              <span class="keyword">continue</span>;
            }

            <span class="keyword">if</span> (<span class="string">'$type'</span> === $cond) {
              <span class="keyword">if</span> (<span class="string">'number'</span> !== <span class="keyword">typeof</span> nested) {
                <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">"$type parameter must be Number"</span>);
              }
              <span class="keyword">continue</span>;
            }

            <span class="keyword">if</span> (<span class="string">'$not'</span> === $cond) {
              <span class="keyword">this</span>.cast(model, nested);
            } <span class="keyword">else</span> {
              val[$cond] = schematype.castForQuery($cond, nested);
            }
          }
        }
      } <span class="keyword">else</span> {
        obj[path] = schematype.castForQuery(val);
      }
    }
  }

  <span class="keyword">return</span> obj;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>model</code><span class="types"> &lt;<a href="#model_Model">Model</a>&gt; </span><span></span></li><li><code>[obj]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="description"><h4>Note</h4>

<p>If <code>obj</code> is present, it is cast instead of this query.</p></div><hr class=""></div><div class="item method private"><h3 id="query_Query-_optionsForExec"><a href="#query_Query-_optionsForExec">Query#_optionsForExec(<code>model</code>)</a></h3><p>Returns default options.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype._optionsForExec = <span class="function"><span class="keyword">function</span> <span class="params">(model)</span> {</span>
  <span class="keyword">var</span> options = utils.clone(<span class="keyword">this</span>.options, { retainKeyOrder: <span class="literal">true</span> });
  <span class="keyword">delete</span> options.populate;

  <span class="keyword">if</span> (!(<span class="string">'batchSize'</span> <span class="keyword">in</span> options))
    options.batchSize = <span class="number">1000</span>;

  <span class="keyword">if</span> (!(<span class="string">'safe'</span> <span class="keyword">in</span> options))
    options.safe = model.schema.options.safe;

  <span class="keyword">if</span> (!(<span class="string">'readPreference'</span> <span class="keyword">in</span> options) &amp;&amp; model.schema.options.read)
    options.readPreference = model.schema.options.read;

  <span class="keyword">return</span> options;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>model</code><span class="types"> &lt;<a href="#model_Model">Model</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="query_Query-_applyPaths"><a href="#query_Query-_applyPaths">Query#_applyPaths()</a></h3><p>Applies schematype selected options to this query.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype._applyPaths = <span class="function"><span class="keyword">function</span> <span class="title">applyPaths</span> <span class="params">()</span> {</span>
  <span class="comment">// determine if query is selecting or excluding fields</span>

  <span class="keyword">var</span> fields = <span class="keyword">this</span>._fields
    , exclude
    , keys
    , ki

  <span class="keyword">if</span> (fields) {
    keys = Object.keys(fields);
    ki = keys.length;

    <span class="keyword">while</span> (ki--) {
      <span class="keyword">if</span> (<span class="string">'+'</span> == keys[ki][<span class="number">0</span>]) <span class="keyword">continue</span>;
      exclude = <span class="number">0</span> === fields[keys[ki]];
      <span class="keyword">break</span>;
    }
  }

  <span class="comment">// if selecting, apply default schematype select:true fields</span>
  <span class="comment">// if excluding, apply schematype select:false fields</span>

  <span class="keyword">var</span> selected = []
    , excluded = []
    , seen = [];

  analyzeSchema(<span class="keyword">this</span>.model.schema);

  <span class="keyword">switch</span> (exclude) {
    <span class="keyword">case</span> <span class="literal">true</span>:
      excluded.length &amp;&amp; <span class="keyword">this</span>.select(<span class="string">'-'</span> + excluded.join(<span class="string">' -'</span>));
      <span class="keyword">break</span>;
    <span class="keyword">case</span> <span class="literal">false</span>:
      selected.length &amp;&amp; <span class="keyword">this</span>.select(selected.join(<span class="string">' '</span>));
      <span class="keyword">break</span>;
    <span class="keyword">case</span> <span class="literal">undefined</span>:
      <span class="comment">// user didn't specify fields, implies returning all fields.</span>
      <span class="comment">// only need to apply excluded fields</span>
      excluded.length &amp;&amp; <span class="keyword">this</span>.select(<span class="string">'-'</span> + excluded.join(<span class="string">' -'</span>));
      <span class="keyword">break</span>;
  }

  <span class="keyword">return</span> seen = excluded = selected = keys = fields = <span class="literal">null</span>;

  <span class="function"><span class="keyword">function</span> <span class="title">analyzeSchema</span> <span class="params">(schema, prefix)</span> {</span>
    prefix || (prefix = <span class="string">''</span>);

    <span class="comment">// avoid recursion</span>
    <span class="keyword">if</span> (~seen.indexOf(schema)) <span class="keyword">return</span>;
    seen.push(schema);

    schema.eachPath(<span class="function"><span class="keyword">function</span> <span class="params">(path, type)</span> {</span>
      <span class="keyword">if</span> (prefix) path = prefix + <span class="string">'.'</span> + path;

      <span class="comment">// array of subdocs?</span>
      <span class="keyword">if</span> (type.schema) {
        analyzeSchema(type.schema, path);
      }

      analyzePath(path, type);
    });
  }

  <span class="function"><span class="keyword">function</span> <span class="title">analyzePath</span> <span class="params">(path, type)</span> {</span>
    <span class="keyword">if</span> (<span class="string">'boolean'</span> != <span class="keyword">typeof</span> type.selected) <span class="keyword">return</span>;

    <span class="keyword">if</span> (fields &amp;&amp; (<span class="string">'+'</span> + path) <span class="keyword">in</span> fields) {
      <span class="comment">// forced inclusion</span>
      <span class="keyword">delete</span> fields[<span class="string">'+'</span> + path];

      <span class="comment">// if there are other fields being included, add this one</span>
      <span class="comment">// if no other included fields, leave this out (implied inclusion)</span>
      <span class="keyword">if</span> (<span class="literal">false</span> === exclude &amp;&amp; keys.length > <span class="number">1</span>) {
        fields[path] = <span class="number">1</span>;
      }

      <span class="keyword">return</span>
    };

    ;(type.selected ? selected : excluded).push(path);
  }
}</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="query_Query-%24where"><a href="#query_Query-%24where">Query#$where(<code>js</code>)</a></h3><p>Specifies a <code>$where</code> condition</p><div class="params"><h4>Parameters:</h4><ul><li><code>js</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span>javascript string or function</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="description"><p>Use <code>$where</code> when you need to select documents using a JavaScript expression.</p>

<h4>Example</h4>

<pre><code>query.$where(<span class="string">'this.comments.length &amp;gt; 10 || this.name.length &amp;gt; 5'</span>)

query.$where(<span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">return</span> <span class="keyword">this</span>.comments.length &amp;gt; <span class="number">10</span> || <span class="keyword">this</span>.name.length &amp;gt; <span class="number">5</span>;
})</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-where"><a href="#query_Query-where">Query#where(<code>[path]</code>, <code>[val]</code>)</a></h3><p>Specifies a <code>path</code> for use with chaining.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.where = <span class="function"><span class="keyword">function</span> <span class="params">(path, val)</span> {</span>
  <span class="keyword">if</span> (!arguments.length) <span class="keyword">return</span> <span class="keyword">this</span>;

  <span class="keyword">if</span> (<span class="string">'string'</span> != <span class="keyword">typeof</span> path) {
    <span class="keyword">throw</span> <span class="keyword">new</span> TypeError(<span class="string">'path must be a string'</span>);
  }

  <span class="keyword">this</span>._currPath = path;

  <span class="keyword">if</span> (<span class="number">2</span> === arguments.length) {
    <span class="keyword">this</span>._conditions[path] = val;
  }

  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>[path]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>[val]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="description"><h4>Example</h4>

<pre><code><span class="comment">// instead of writing:</span>
User.find({age: {$gte: <span class="number">21</span>, $lte: <span class="number">65</span>}}, callback);

<span class="comment">// we can instead write:</span>
User.where(<span class="string">'age'</span>).gte(<span class="number">21</span>).lte(<span class="number">65</span>);

<span class="comment">// Moreover, you can also chain a bunch of these together:</span>

User
.where(<span class="string">'age'</span>).gte(<span class="number">21</span>).lte(<span class="number">65</span>)
.where(<span class="string">'name'</span>, <span class="regexp">/^b/i</span>)
.where(<span class="string">'friends'</span>).slice(<span class="number">10</span>)
.exec(callback)</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-equals"><a href="#query_Query-equals">Query#equals(<code>val</code>)</a></h3><p>Specifies the complementary comparison value for paths specified with <code>where()</code></p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.equals = <span class="function"><span class="keyword">function</span> <span class="title">equals</span> <span class="params">(val)</span> {</span>
  <span class="keyword">var</span> path = <span class="keyword">this</span>._currPath;
  <span class="keyword">if</span> (!path) <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">'equals() must be used after where()'</span>);
  <span class="keyword">this</span>._conditions[path] = val;
  <span class="keyword">return</span> <span class="keyword">this</span>;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="description"><h4>Example</h4>

<pre><code>User.where(<span class="string">'age'</span>).equals(<span class="number">49</span>);

<span class="comment">// is the same as</span>

User.where(<span class="string">'age'</span>, <span class="number">49</span>);</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-or"><a href="#query_Query-or">Query#or(<code>array</code>)</a></h3><p>Specifies arguments for an <code>$or</code> condition.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.or = <span class="function"><span class="keyword">function</span> <span class="title">or</span> <span class="params">(array)</span> {</span>
  <span class="keyword">var</span> or = <span class="keyword">this</span>._conditions.$or || (<span class="keyword">this</span>._conditions.$or = []);
  <span class="keyword">if</span> (!Array.isArray(array)) array = [array];
  or.push.apply(or, array);
  <span class="keyword">return</span> <span class="keyword">this</span>;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>array</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array">Array</a>&gt; </span><span>array of conditions</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="description"><h4>Example</h4>

<pre><code>query.or([{ color: <span class="string">'red'</span> }, { status: <span class="string">'emergency'</span> }])</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-nor"><a href="#query_Query-nor">Query#nor(<code>array</code>)</a></h3><p>Specifies arguments for a <code>$nor</code> condition.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.nor = <span class="function"><span class="keyword">function</span> <span class="title">nor</span> <span class="params">(array)</span> {</span>
  <span class="keyword">var</span> nor = <span class="keyword">this</span>._conditions.$nor || (<span class="keyword">this</span>._conditions.$nor = []);
  <span class="keyword">if</span> (!Array.isArray(array)) array = [array];
  nor.push.apply(nor, array);
  <span class="keyword">return</span> <span class="keyword">this</span>;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>array</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array">Array</a>&gt; </span><span>array of conditions</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="description"><h4>Example</h4>

<pre><code>query.nor([{ color: <span class="string">'green'</span> }, { status: <span class="string">'ok'</span> }])</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-gt"><a href="#query_Query-gt">Query#gt(<code>path</code>, <code>val</code>)</a></h3><p>Specifies a $gt query condition.</p><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span></span></li></ul></div><div class="description"><p>When called with one argument, the most recent path passed to <code>where()</code> is used.</p>

<h4>Example</h4>

<pre><code>Thing.find().where(<span class="string">'age'</span>).gt(<span class="number">21</span>)

<span class="comment">// or</span>
Thing.find().gt(<span class="string">'age'</span>, <span class="number">21</span>)</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-gte"><a href="#query_Query-gte">Query#gte(<code>path</code>, <code>val</code>)</a></h3><p>Specifies a $gte query condition.</p><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span></span></li></ul></div><div class="description"><p>When called with one argument, the most recent path passed to <code>where()</code> is used.</p></div><hr class=""></div><div class="item method public"><h3 id="query_Query-lt"><a href="#query_Query-lt">Query#lt(<code>path</code>, <code>val</code>)</a></h3><p>Specifies a $lt query condition.</p><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span></span></li></ul></div><div class="description"><p>When called with one argument, the most recent path passed to <code>where()</code> is used.</p></div><hr class=""></div><div class="item method public"><h3 id="query_Query-lte"><a href="#query_Query-lte">Query#lte(<code>path</code>, <code>val</code>)</a></h3><p>Specifies a $lte query condition.</p><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span></span></li></ul></div><div class="description"><p>When called with one argument, the most recent path passed to <code>where()</code> is used.</p></div><hr class=""></div><div class="item method public"><h3 id="query_Query-ne"><a href="#query_Query-ne">Query#ne(<code>path</code>, <code>val</code>)</a></h3><p>Specifies a $ne query condition.</p><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span></span></li></ul></div><div class="description"><p>When called with one argument, the most recent path passed to <code>where()</code> is used.</p></div><hr class=""></div><div class="item method public"><h3 id="query_Query-in"><a href="#query_Query-in">Query#in(<code>path</code>, <code>val</code>)</a></h3><p>Specifies an $in query condition.</p><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span></span></li></ul></div><div class="description"><p>When called with one argument, the most recent path passed to <code>where()</code> is used.</p></div><hr class=""></div><div class="item method public"><h3 id="query_Query-nin"><a href="#query_Query-nin">Query#nin(<code>path</code>, <code>val</code>)</a></h3><p>Specifies an $nin query condition.</p><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span></span></li></ul></div><div class="description"><p>When called with one argument, the most recent path passed to <code>where()</code> is used.</p></div><hr class=""></div><div class="item method public"><h3 id="query_Query-all"><a href="#query_Query-all">Query#all(<code>path</code>, <code>val</code>)</a></h3><p>Specifies an $all query condition.</p><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span></span></li></ul></div><div class="description"><p>When called with one argument, the most recent path passed to <code>where()</code> is used.</p></div><hr class=""></div><div class="item method public"><h3 id="query_Query-size"><a href="#query_Query-size">Query#size(<code>path</code>, <code>val</code>)</a></h3><p>Specifies an $size query condition.</p><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span></span></li></ul></div><div class="description"><p>When called with one argument, the most recent path passed to <code>where()</code> is used.</p></div><hr class=""></div><div class="item method public"><h3 id="query_Query-regex"><a href="#query_Query-regex">Query#regex(<code>path</code>, <code>val</code>)</a></h3><p>Specifies a $regex query condition.</p><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span></span></li></ul></div><div class="description"><p>When called with one argument, the most recent path passed to <code>where()</code> is used.</p></div><hr class=""></div><div class="item method public"><h3 id="query_Query-maxDistance"><a href="#query_Query-maxDistance">Query#maxDistance(<code>path</code>, <code>val</code>)</a></h3><p>Specifies a $maxDistance query condition.</p><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span></span></li></ul></div><div class="description"><p>When called with one argument, the most recent path passed to <code>where()</code> is used.</p></div><hr class=""></div><div class="item method public"><h3 id="query_Query-near"><a href="#query_Query-near">Query#near(<code>path</code>, <code>val</code>)</a></h3><p>Specifies a <code>$near</code> condition</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.near = <span class="function"><span class="keyword">function</span> <span class="params">(path, val)</span> {</span>
  <span class="keyword">if</span> (arguments.length === <span class="number">1</span>) {
    val = path;
    path = <span class="keyword">this</span>._currPath
  } <span class="keyword">else</span> <span class="keyword">if</span> (arguments.length === <span class="number">2</span> &amp;&amp; !Array.isArray(val)) {
    val = utils.args(arguments);
    path = <span class="keyword">this</span>._currPath;
  } <span class="keyword">else</span> <span class="keyword">if</span> (arguments.length === <span class="number">3</span>) {
    val = utils.args(arguments, <span class="number">1</span>);
  }
  <span class="keyword">var</span> conds = <span class="keyword">this</span>._conditions[path] || (<span class="keyword">this</span>._conditions[path] = {});
  conds.$near = val;
  <span class="keyword">return</span> <span class="keyword">this</span>;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/Geospatial+Indexing">http://www.mongodb.org/display/DOCS/Geospatial+Indexing</a></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="query_Query-nearSphere"><a href="#query_Query-nearSphere">Query#nearSphere(<code>path</code>, <code>val</code>)</a></h3><p>Specifies a <code>$nearSphere</code> condition.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.nearSphere = <span class="function"><span class="keyword">function</span> <span class="params">(path, val)</span> {</span>
  <span class="keyword">if</span> (arguments.length === <span class="number">1</span>) {
    val = path;
    path = <span class="keyword">this</span>._currPath
  } <span class="keyword">else</span> <span class="keyword">if</span> (arguments.length === <span class="number">2</span> &amp;&amp; !Array.isArray(val)) {
    val = utils.args(arguments);
    path = <span class="keyword">this</span>._currPath;
  } <span class="keyword">else</span> <span class="keyword">if</span> (arguments.length === <span class="number">3</span>) {
    val = utils.args(arguments, <span class="number">1</span>);
  }
  <span class="keyword">var</span> conds = <span class="keyword">this</span>._conditions[path] || (<span class="keyword">this</span>._conditions[path] = {});
  conds.$nearSphere = val;
  <span class="keyword">return</span> <span class="keyword">this</span>;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/Geospatial+Indexing">http://www.mongodb.org/display/DOCS/Geospatial+Indexing</a></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="query_Query-mod"><a href="#query_Query-mod">Query#mod(<code>path</code>, <code>val</code>)</a></h3><p>Specifies a <code>$mod</code> condition</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.mod = <span class="function"><span class="keyword">function</span> <span class="params">(path, val)</span> {</span>
  <span class="keyword">if</span> (arguments.length === <span class="number">1</span>) {
    val = path;
    path = <span class="keyword">this</span>._currPath
  } <span class="keyword">else</span> <span class="keyword">if</span> (arguments.length === <span class="number">2</span> &amp;&amp; !Array.isArray(val)) {
    val = utils.args(arguments);
    path = <span class="keyword">this</span>._currPath;
  } <span class="keyword">else</span> <span class="keyword">if</span> (arguments.length === <span class="number">3</span>) {
    val = utils.args(arguments, <span class="number">1</span>);
  }
  <span class="keyword">var</span> conds = <span class="keyword">this</span>._conditions[path] || (<span class="keyword">this</span>._conditions[path] = {});
  conds.$mod = val;
  <span class="keyword">return</span> <span class="keyword">this</span>;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="query_Query-exists"><a href="#query_Query-exists">Query#exists(<code>path</code>, <code>val</code>)</a></h3><p>Specifies an <code>$exists</code> condition</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.exists = <span class="function"><span class="keyword">function</span> <span class="params">(path, val)</span> {</span>
  <span class="keyword">if</span> (arguments.length === <span class="number">0</span>) {
    path = <span class="keyword">this</span>._currPath
    val = <span class="literal">true</span>;
  } <span class="keyword">else</span> <span class="keyword">if</span> (arguments.length === <span class="number">1</span>) {
    <span class="keyword">if</span> (<span class="string">'boolean'</span> === <span class="keyword">typeof</span> path) {
      val = path;
      path = <span class="keyword">this</span>._currPath;
    } <span class="keyword">else</span> {
      val = <span class="literal">true</span>;
    }
  }
  <span class="keyword">var</span> conds = <span class="keyword">this</span>._conditions[path] || (<span class="keyword">this</span>._conditions[path] = {});
  conds[<span class="string">'$exists'</span>] = val;
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="query_Query-elemMatch"><a href="#query_Query-elemMatch">Query#elemMatch(<code>path</code>, <code>criteria</code>)</a></h3><p>Specifies an <code>$elemMatch</code> condition</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.elemMatch = <span class="function"><span class="keyword">function</span> <span class="params">(path, criteria)</span> {</span>
  <span class="keyword">var</span> block;
  <span class="keyword">if</span> (<span class="string">'Object'</span> === path.constructor.name) {
    criteria = path;
    path = <span class="keyword">this</span>._currPath;
  } <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">'function'</span> === <span class="keyword">typeof</span> path) {
    block = path;
    path = <span class="keyword">this</span>._currPath;
  } <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">'Object'</span> === criteria.constructor.name) {
  } <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">'function'</span> === <span class="keyword">typeof</span> criteria) {
    block = criteria;
  } <span class="keyword">else</span> {
    <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">"Argument error"</span>);
  }
  <span class="keyword">var</span> conds = <span class="keyword">this</span>._conditions[path] || (<span class="keyword">this</span>._conditions[path] = {});
  <span class="keyword">if</span> (block) {
    criteria = <span class="keyword">new</span> Query();
    block(criteria);
    conds[<span class="string">'$elemMatch'</span>] = criteria._conditions;
  } <span class="keyword">else</span> {
    conds[<span class="string">'$elemMatch'</span>] = criteria;
  }
  <span class="keyword">return</span> <span class="keyword">this</span>;
};

<span class="comment">// Spatial queries</span></code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li><li><code>criteria</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="description"><h4>Example</h4>

<pre><code>query.elemMatch(<span class="string">'comment'</span>, { author: <span class="string">'autobot'</span>, votes: {$gte: <span class="number">5</span>}})

query.where(<span class="string">'comment'</span>).elemMatch({ author: <span class="string">'autobot'</span>, votes: {$gte: <span class="number">5</span>}})

query.elemMatch(<span class="string">'comment'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(elem)</span> {</span>
  elem.where(<span class="string">'author'</span>).equals(<span class="string">'autobot'</span>);
  elem.where(<span class="string">'votes'</span>).gte(<span class="number">5</span>);
})

query.where(<span class="string">'comment'</span>).elemMatch(<span class="function"><span class="keyword">function</span> <span class="params">(elem)</span> {</span>
  elem.where(<span class="string">'author'</span>).equals(<span class="string">'autobot'</span>);
  elem.where(<span class="string">'votes'</span>).gte(<span class="number">5</span>);
})</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-box"><a href="#query_Query-box">Query#box(<code>path</code>, <code>val</code>)</a></h3><p>Specifies a $box condition</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.box = <span class="function"><span class="keyword">function</span> <span class="params">(path, val)</span> {</span>
  <span class="keyword">if</span> (arguments.length === <span class="number">1</span>) {
    val = path;
    path = <span class="keyword">this</span>._currPath;
  }
  <span class="keyword">var</span> conds = <span class="keyword">this</span>._conditions[path] || (<span class="keyword">this</span>._conditions[path] = {});
  conds[<span class="string">'$within'</span>] = { <span class="string">'$box'</span>: [val.ll, val.ur]  };
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/Geospatial+Indexing">http://www.mongodb.org/display/DOCS/Geospatial+Indexing</a></li><li><a href="#query_Query-within" title="Query#within">Query#within</a></li></ul></div><div class="description"><h4>Example</h4>

<pre><code><span class="keyword">var</span> lowerLeft = [<span class="number">40.73083</span>, -<span class="number">73.99756</span>]
<span class="keyword">var</span> upperRight= [<span class="number">40.741404</span>,  -<span class="number">73.988135</span>]
query.where(<span class="string">'loc'</span>).within.box({ ll: lowerLeft , ur: upperRight })</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-center"><a href="#query_Query-center">Query#center(<code>path</code>, <code>val</code>, <code>[opts]</code>)</a></h3><p>Specifies a $center condition</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.center = <span class="function"><span class="keyword">function</span> <span class="params">(path, val, opts)</span> {</span>
  <span class="keyword">if</span> (arguments.length === <span class="number">1</span>) {
    val = path;
    path = <span class="keyword">this</span>._currPath;
  }
  <span class="keyword">var</span> conds = <span class="keyword">this</span>._conditions[path] || (<span class="keyword">this</span>._conditions[path] = {});
  conds[<span class="string">'$within'</span>] = { <span class="string">'$center'</span>: [val.center, val.radius]  };

  <span class="comment">// copy any options</span>
  <span class="keyword">if</span> (opts &amp;&amp; <span class="string">'Object'</span> == opts.constructor.name) {
    utils.options(opts, conds.$within);
  }

  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[opts]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>options e.g. { $uniqueDocs: true }</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/Geospatial+Indexing">http://www.mongodb.org/display/DOCS/Geospatial+Indexing</a></li></ul></div><div class="description"><h4>Example</h4>

<pre><code><span class="keyword">var</span> area = { center: [<span class="number">50</span>, <span class="number">50</span>], radius: <span class="number">10</span> }
query.where(<span class="string">'loc'</span>).within.center(area)</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-centerSphere"><a href="#query_Query-centerSphere">Query#centerSphere(<code>path</code>, <code>val</code>)</a></h3><p>Specifies a $centerSphere condition</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.centerSphere = <span class="function"><span class="keyword">function</span> <span class="params">(path, val)</span> {</span>
  <span class="keyword">if</span> (arguments.length === <span class="number">1</span>) {
    val = path;
    path = <span class="keyword">this</span>._currPath;
  }
  <span class="keyword">var</span> conds = <span class="keyword">this</span>._conditions[path] || (<span class="keyword">this</span>._conditions[path] = {});
  conds[<span class="string">'$within'</span>] = { <span class="string">'$centerSphere'</span>: [val.center, val.radius]  };
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/Geospatial+Indexing">http://www.mongodb.org/display/DOCS/Geospatial+Indexing</a></li></ul></div><div class="description"><h4>Example</h4>

<pre><code><span class="keyword">var</span> area = { center: [<span class="number">50</span>, <span class="number">50</span>], radius: <span class="number">10</span> }
query.where(<span class="string">'loc'</span>).within.centerSphere(area)</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-polygon"><a href="#query_Query-polygon">Query#polygon(<code>path</code>, <code>val</code>)</a></h3><p>Specifies a $polygon condition</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.polygon = <span class="function"><span class="keyword">function</span> <span class="params">(path, val)</span> {</span>
  <span class="keyword">if</span> (arguments.length === <span class="number">1</span>) {
    val = path;
    path = <span class="keyword">this</span>._currPath;
  }
  <span class="keyword">var</span> conds = <span class="keyword">this</span>._conditions[path] || (<span class="keyword">this</span>._conditions[path] = {});
  conds[<span class="string">'$within'</span>] = { <span class="string">'$polygon'</span>: val };
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array">Array</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/Geospatial+Indexing">http://www.mongodb.org/display/DOCS/Geospatial+Indexing</a></li></ul></div><div class="description"><h4>Example</h4>

<pre><code><span class="keyword">var</span> polyA = [ [ <span class="number">10</span>, <span class="number">20</span> ], [ <span class="number">10</span>, <span class="number">40</span> ], [ <span class="number">30</span>, <span class="number">40</span> ], [ <span class="number">30</span>, <span class="number">20</span> ] ]
query.where(<span class="string">'loc'</span>).within.polygon(polyA)

<span class="comment">// or</span>
<span class="keyword">var</span> polyB = { a : { x : <span class="number">10</span>, y : <span class="number">20</span> }, b : { x : <span class="number">15</span>, y : <span class="number">25</span> }, c : { x : <span class="number">20</span>, y : <span class="number">20</span> } }
query.where(<span class="string">'loc'</span>).within.polygon(polyB)</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-select"><a href="#query_Query-select">Query#select(<code>arg</code>)</a></h3><p>Specifies which document fields to include or exclude</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.select = <span class="function"><span class="keyword">function</span> <span class="title">select</span> <span class="params">(arg)</span> {</span>
  <span class="keyword">if</span> (!arg) <span class="keyword">return</span> <span class="keyword">this</span>;

  <span class="keyword">var</span> fields = <span class="keyword">this</span>._fields || (<span class="keyword">this</span>._fields = {});

  <span class="keyword">if</span> (<span class="string">'Object'</span> === arg.constructor.name) {
    Object.keys(arg).forEach(<span class="function"><span class="keyword">function</span> <span class="params">(field)</span> {</span>
      fields[field] = arg[field];
    });
  } <span class="keyword">else</span> <span class="keyword">if</span> (<span class="number">1</span> === arguments.length &amp;&amp; <span class="string">'string'</span> == <span class="keyword">typeof</span> arg) {
    arg.split(<span class="regexp">/\s+/</span>).forEach(<span class="function"><span class="keyword">function</span> <span class="params">(field)</span> {</span>
      <span class="keyword">if</span> (!field) <span class="keyword">return</span>;
      <span class="keyword">var</span> include = <span class="string">'-'</span> == field[<span class="number">0</span>] ? <span class="number">0</span> : <span class="number">1</span>;
      <span class="keyword">if</span> (include === <span class="number">0</span>) field = field.substring(<span class="number">1</span>);
      fields[field] = include;
    });
  } <span class="keyword">else</span> {
    <span class="keyword">throw</span> <span class="keyword">new</span> TypeError(<span class="string">'Invalid select() argument. Must be a string or object.'</span>);
  }

  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>arg</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="#schematype_SchemaType" title="SchemaType">SchemaType</a></li></ul></div><div class="description"><p>When using string syntax, prefixing a path with <code>-</code> will flag that path as excluded. When a path does not have the <code>-</code> prefix, it is included. Lastly, if a path is prefixed with <code>+</code>, it forces inclusion of the path, which is useful for paths excluded at the <a href="./api.html#schematype_SchemaType-select">schema level</a>.</p>

<h4>Example</h4>

<pre><code><span class="comment">// include a and b, exclude c</span>
query.select(<span class="string">'a b -c'</span>);

<span class="comment">// or you may use object notation, useful when</span>
<span class="comment">// you have keys already prefixed with a "-"</span>
query.select({a: <span class="number">1</span>, b: <span class="number">1</span>, c: <span class="number">0</span>});

<span class="comment">// force inclusion of field excluded at schema level</span>
query.select(<span class="string">'+path'</span>)</code></pre>

<h4>NOTE:</h4>

<p><em>v2 had slightly different syntax such as allowing arrays of field names. This support was removed in v3.</em></p></div><hr class=""></div><div class="item method public"><h3 id="query_Query-slice"><a href="#query_Query-slice">Query#slice(<code>path</code>, <code>val</code>)</a></h3><p>Specifies a $slice condition</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.slice = <span class="function"><span class="keyword">function</span> <span class="params">(path, val)</span> {</span>
  <span class="keyword">if</span> (arguments.length === <span class="number">1</span>) {
      val = path;
      path = <span class="keyword">this</span>._currPath
  } <span class="keyword">else</span> <span class="keyword">if</span> (arguments.length === <span class="number">2</span>) {
    <span class="keyword">if</span> (<span class="string">'number'</span> === <span class="keyword">typeof</span> path) {
      val = [path, val];
      path = <span class="keyword">this</span>._currPath;
    }
  } <span class="keyword">else</span> <span class="keyword">if</span> (arguments.length === <span class="number">3</span>) {
    val = utils.args(arguments, <span class="number">1</span>);
  }
  <span class="keyword">var</span> myFields = <span class="keyword">this</span>._fields || (<span class="keyword">this</span>._fields = {});
  myFields[path] = { <span class="string">'$slice'</span>: val };
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span>number of elements to slice</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/Retrieving+a+Subset+of+Fields#RetrievingaSubsetofFields-RetrievingaSubrangeofArrayElements" title="mongodb">mongodb</a></li></ul></div><div class="description"><h4>Example</h4>

<pre><code>query.slice(<span class="string">'comments'</span>, <span class="number">5</span>)
query.slice(<span class="string">'comments'</span>, -<span class="number">5</span>)
query.slice(<span class="string">'comments'</span>, [<span class="number">10</span>, <span class="number">5</span>])
query.where(<span class="string">'comments'</span>).slice(<span class="number">5</span>)
query.where(<span class="string">'comments'</span>).slice([-<span class="number">10</span>, <span class="number">5</span>])</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-sort"><a href="#query_Query-sort">Query#sort(<code>arg</code>)</a></h3><p>Sets the sort order</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.sort = <span class="function"><span class="keyword">function</span> <span class="params">(arg)</span> {</span>
  <span class="keyword">if</span> (!arg) <span class="keyword">return</span> <span class="keyword">this</span>;

  <span class="keyword">var</span> sort = <span class="keyword">this</span>.options.sort || (<span class="keyword">this</span>.options.sort = []);

  <span class="keyword">if</span> (<span class="string">'Object'</span> === arg.constructor.name) {
    Object.keys(arg).forEach(<span class="function"><span class="keyword">function</span> <span class="params">(field)</span> {</span>
      push(sort, field, arg[field]);
    });
  } <span class="keyword">else</span> <span class="keyword">if</span> (<span class="number">1</span> === arguments.length &amp;&amp; <span class="string">'string'</span> == <span class="keyword">typeof</span> arg) {
    arg.split(<span class="regexp">/\s+/</span>).forEach(<span class="function"><span class="keyword">function</span> <span class="params">(field)</span> {</span>
      <span class="keyword">if</span> (!field) <span class="keyword">return</span>;
      <span class="keyword">var</span> ascend = <span class="string">'-'</span> == field[<span class="number">0</span>] ? -<span class="number">1</span> : <span class="number">1</span>;
      <span class="keyword">if</span> (ascend === -<span class="number">1</span>) field = field.substring(<span class="number">1</span>);
      push(sort, field, ascend);
    });
  } <span class="keyword">else</span> {
    <span class="keyword">throw</span> <span class="keyword">new</span> TypeError(<span class="string">'Invalid sort() argument. Must be a string or object.'</span>);
  }

  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>arg</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="description"><p>If an object is passed, values allowed are 'asc', 'desc', 'ascending', 'descending', 1, and -1.</p>

<p>If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with <code>-</code> which will be treated as descending.</p>

<h4>Example</h4>

<pre><code><span class="comment">// these are equivalent</span>
query.sort({ field: <span class="string">'asc'</span>, test: -<span class="number">1</span> });
query.sort(<span class="string">'field -test'</span>);</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-limit"><a href="#query_Query-limit">Query#limit(<code>val</code>)</a></h3><p>Specifies the limit option.</p><div class="params"><h4>Parameters:</h4><ul><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span></span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Blimit%28%29%7D%7D" title="mongodb">mongodb</a></li></ul></div><div class="description"><h4>Example</h4>

<pre><code>Kitten.find().limit(<span class="number">20</span>)</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-skip"><a href="#query_Query-skip">Query#skip(<code>val</code>)</a></h3><p>Specifies the skip option.</p><div class="params"><h4>Parameters:</h4><ul><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span></span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bskip%28%29%7D%7D" title="mongodb">mongodb</a></li></ul></div><div class="description"><h4>Example</h4>

<pre><code>Kitten.find().skip(<span class="number">100</span>).limit(<span class="number">20</span>)</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-maxscan"><a href="#query_Query-maxscan">Query#maxscan(<code>val</code>)</a></h3><p>Specifies the maxscan option.</p><div class="params"><h4>Parameters:</h4><ul><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span></span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24maxScan" title="mongodb">mongodb</a></li></ul></div><div class="description"><h4>Example</h4>

<pre><code>Kitten.find().maxscan(<span class="number">100</span>)</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-batchSize"><a href="#query_Query-batchSize">Query#batchSize(<code>val</code>)</a></h3><p>Specifies the batchSize option.</p><div class="params"><h4>Parameters:</h4><ul><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span></span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7BbatchSize%28%29%7D%7D" title="mongodb">mongodb</a></li></ul></div><div class="description"><h4>Example</h4>

<pre><code>Kitten.find().batchSize(<span class="number">100</span>)</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-comment"><a href="#query_Query-comment">Query#comment(<code>val</code>)</a></h3><p>Specifies the <code>comment</code> option.</p><div class="params"><h4>Parameters:</h4><ul><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span></span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24comment" title="mongodb">mongodb</a></li></ul></div><div class="description"><h4>Example</h4>

<pre><code>Kitten.findOne(condition).comment(<span class="string">'login query'</span>)</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-snapshot"><a href="#query_Query-snapshot">Query#snapshot()</a></h3><p>Specifies this query as a <code>snapshot</code> query.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.snapshot = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">this</span>.options.snapshot = <span class="literal">true</span>;
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%7B%7Bsnapshot%28%29%7D%7D" title="mongodb">mongodb</a></li></ul></div><div class="description"><h4>Example</h4>

<pre><code>Kitten.find().snapshot()</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-hint"><a href="#query_Query-hint">Query#hint(<code>val</code>)</a></h3><p>Sets query hints.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.hint = <span class="function"><span class="keyword">function</span> <span class="params">(val)</span> {</span>
  <span class="keyword">if</span> (!val) <span class="keyword">return</span> <span class="keyword">this</span>;

  <span class="keyword">var</span> hint = <span class="keyword">this</span>.options.hint || (<span class="keyword">this</span>.options.hint = {});

  <span class="keyword">if</span> (<span class="string">'Object'</span> === val.constructor.name) {
    <span class="comment">// must keep object keys in order so don't use Object.keys()</span>
    <span class="keyword">for</span> (<span class="keyword">var</span> k <span class="keyword">in</span> val) {
      hint[k] = val[k];
    }
  } <span class="keyword">else</span> {
    <span class="keyword">throw</span> <span class="keyword">new</span> TypeError(<span class="string">'Invalid hint. '</span> + val);
  }

  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>a hint object</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/Advanced+Queries#AdvancedQueries-%24hint" title="mongodb">mongodb</a></li></ul></div><div class="description"><h4>Example</h4>

<pre><code>Model.find().hint({ indexA: <span class="number">1</span>, indexB: -<span class="number">1</span>})</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-slaveOk"><a href="#query_Query-slaveOk">Query#slaveOk(<code>v</code>)</a></h3><p>Sets the slaveOk option.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.slaveOk = <span class="function"><span class="keyword">function</span> <span class="params">(v)</span> {</span>
  <span class="keyword">this</span>.options.slaveOk = arguments.length ? !!v : <span class="literal">true</span>;
  <span class="keyword">return</span> <span class="keyword">this</span>;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>v</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span>defaults to true</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://docs.mongodb.org/manual/applications/replication/#read-preference" title="mongodb">mongodb</a></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code><span class="keyword">new</span> Query().slaveOk() <span class="comment">// true</span>
<span class="keyword">new</span> Query().slaveOk(<span class="literal">true</span>)
<span class="keyword">new</span> Query().slaveOk(<span class="literal">false</span>)</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-read"><a href="#query_Query-read">Query#read(<code>pref</code>, <code>[tags]</code>)</a></h3><p>Sets the readPreference option for the query.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.read = <span class="function"><span class="keyword">function</span> <span class="params">(pref, tags)</span> {</span>
  <span class="keyword">this</span>.options.readPreference = utils.readPref(pref, tags);
  <span class="keyword">return</span> <span class="keyword">this</span>;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>pref</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>one of the listed preference options or their aliases</span></li><li><code>[tags]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array">Array</a>&gt; </span><span>optional tags for this query</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://docs.mongodb.org/manual/applications/replication/#read-preference" title="mongodb">mongodb</a></li><li><a href="http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences" title="driver">driver</a></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code><span class="keyword">new</span> Query().read(<span class="string">'primary'</span>)
<span class="keyword">new</span> Query().read(<span class="string">'p'</span>)  <span class="comment">// same as primary</span>

<span class="keyword">new</span> Query().read(<span class="string">'primaryPreferred'</span>)
<span class="keyword">new</span> Query().read(<span class="string">'pp'</span>) <span class="comment">// same as primaryPreferred</span>

<span class="keyword">new</span> Query().read(<span class="string">'secondary'</span>)
<span class="keyword">new</span> Query().read(<span class="string">'s'</span>)  <span class="comment">// same as secondary</span>

<span class="keyword">new</span> Query().read(<span class="string">'secondaryPreferred'</span>)
<span class="keyword">new</span> Query().read(<span class="string">'sp'</span>) <span class="comment">// same as secondaryPreferred</span>

<span class="keyword">new</span> Query().read(<span class="string">'nearest'</span>)
<span class="keyword">new</span> Query().read(<span class="string">'n'</span>)  <span class="comment">// same as nearest</span>

<span class="comment">// with tags</span>
<span class="keyword">new</span> Query().read(<span class="string">'s'</span>, [{ dc:<span class="string">'sf'</span>, s: <span class="number">1</span> },{ dc:<span class="string">'ma'</span>, s: <span class="number">2</span> }])</code></pre>

<h4>Preferences:</h4>

<pre><code>primary - (<span class="keyword">default</span>) Read from primary only. Operations will produce an error <span class="keyword">if</span> primary is unavailable. Cannot be combined <span class="keyword">with</span> tags.
secondary            Read from secondary <span class="keyword">if</span> available, otherwise error.
primaryPreferred     Read from primary <span class="keyword">if</span> available, otherwise a secondary.
secondaryPreferred   Read from a secondary <span class="keyword">if</span> available, otherwise read from the primary.
nearest              All operations read from among the nearest candidates, but unlike other modes, <span class="keyword">this</span> option will include both the primary and all secondaries <span class="keyword">in</span> the random selection.</code></pre>

<p>Aliases</p>

<pre><code>p   primary
pp  primaryPreferred
s   secondary
sp  secondaryPreferred
n   nearest</code></pre>

<p>Read more about how to use read preferrences <a href="http://docs.mongodb.org/manual/applications/replication/#read-preference">here</a> and <a href="http://mongodb.github.com/node-mongodb-native/driver-articles/anintroductionto1_1and2_2.html#read-preferences">here</a>.</p></div><hr class=""></div><div class="item method public"><h3 id="query_Query-lean"><a href="#query_Query-lean">Query#lean(<code>v</code>)</a></h3><p>Sets the lean option.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.lean = <span class="function"><span class="keyword">function</span> <span class="params">(v)</span> {</span>
  <span class="keyword">this</span>.options.lean = arguments.length ? !!v : <span class="literal">true</span>;
  <span class="keyword">return</span> <span class="keyword">this</span>;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>v</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span>defaults to true</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="description"><p>Documents returned from queries with the <code>lean</code> option enabled are plain javascript objects, not <a href="#document-js">MongooseDocuments</a>. They have no <code>save</code> method, getters/setters or any other Mongoose magic applied.</p>

<p>This is a <a href="https://groups.google.com/forum/#!topic/mongoose-orm/u2_DzDydcnA/discussion">great</a> option in high-performance read-only scenarios, especially when combined with the <a href="#query_Query-stream">stream</a> option.</p>

<h4>Example:</h4>

<pre><code><span class="keyword">new</span> Query().lean() <span class="comment">// true</span>
<span class="keyword">new</span> Query().lean(<span class="literal">true</span>)
<span class="keyword">new</span> Query().lean(<span class="literal">false</span>)

Model.find().lean().exec();

<span class="keyword">var</span> leanStream = Model.find().lean().stream();</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-tailable"><a href="#query_Query-tailable">Query#tailable(<code>v</code>)</a></h3><p>Sets tailable option.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.tailable = <span class="function"><span class="keyword">function</span> <span class="params">(v)</span> {</span>
  <span class="keyword">this</span>.options.tailable = arguments.length ? !!v : <span class="literal">true</span>;
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>v</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span>defaults to true</span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/Tailable+Cursors" title="mongodb">mongodb</a></li></ul></div><div class="description"><h4>Example</h4>

<pre><code>Kitten.find().tailable() &amp;lt;== <span class="literal">true</span>
Kitten.find().tailable(<span class="literal">true</span>)
Kitten.find().tailable(<span class="literal">false</span>)</code></pre></div><hr class=""></div><div class="item method private"><h3 id="query_Query-execFind"><a href="#query_Query-execFind">Query#execFind(<code>callback</code>)</a></h3><p>Executes the query as a find() operation.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.execFind = <span class="function"><span class="keyword">function</span> <span class="params">(callback)</span> {</span>
  <span class="keyword">var</span> model = <span class="keyword">this</span>.model
    , promise = <span class="keyword">new</span> Promise(callback);

  <span class="keyword">try</span> {
    <span class="keyword">this</span>.cast(model);
  } <span class="keyword">catch</span> (err) {
    promise.error(err);
    <span class="keyword">return</span> <span class="keyword">this</span>;
  }

  <span class="comment">// apply default schematype path selections</span>
  <span class="keyword">this</span>._applyPaths();

  <span class="keyword">var</span> self = <span class="keyword">this</span>
    , castQuery = <span class="keyword">this</span>._conditions
    , options = <span class="keyword">this</span>._optionsForExec(model)
    , fields = utils.clone(<span class="keyword">this</span>._fields)

  options.fields = <span class="keyword">this</span>._castFields(fields);
  <span class="keyword">if</span> (options.fields <span class="keyword">instanceof</span> Error) {
    promise.error(options.fields);
    <span class="keyword">return</span> <span class="keyword">this</span>;
  }

  model.collection.find(castQuery, options, <span class="function"><span class="keyword">function</span> <span class="params">(err, cursor)</span> {</span>
    <span class="keyword">if</span> (err) <span class="keyword">return</span> promise.error(err);
    cursor.toArray(tick(cb));
  });

  <span class="function"><span class="keyword">function</span> <span class="title">cb</span> <span class="params">(err, docs)</span> {</span>
    <span class="keyword">if</span> (err) <span class="keyword">return</span> promise.error(err);

    <span class="keyword">if</span> (<span class="literal">true</span> === options.lean)
      <span class="keyword">return</span> promise.complete(docs);

    <span class="keyword">var</span> arr = []
      , count = docs.length;

    <span class="keyword">if</span> (!count) <span class="keyword">return</span> promise.complete([]);

    <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>, l = docs.length; i &lt; l; i++) {
      arr[i] = <span class="keyword">new</span> model(<span class="literal">undefined</span>, fields, <span class="literal">true</span>);
      arr[i].init(docs[i], self, <span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
        <span class="keyword">if</span> (err) <span class="keyword">return</span> promise.error(err);
        --count || promise.complete(arr);
      });
    }
  }

  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>callback</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="query_Query-findOne"><a href="#query_Query-findOne">Query#findOne(<code>callback</code>)</a></h3><p>Executes the query as a findOne() operation.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.findOne = <span class="function"><span class="keyword">function</span> <span class="params">(callback)</span> {</span>
  <span class="keyword">this</span>.op = <span class="string">'findOne'</span>;

  <span class="keyword">if</span> (!callback) <span class="keyword">return</span> <span class="keyword">this</span>;

  <span class="keyword">var</span> model = <span class="keyword">this</span>.model;
  <span class="keyword">var</span> promise = <span class="keyword">new</span> Promise(callback);

  <span class="keyword">try</span> {
    <span class="keyword">this</span>.cast(model);
  } <span class="keyword">catch</span> (err) {
    promise.error(err);
    <span class="keyword">return</span> <span class="keyword">this</span>;
  }

  <span class="comment">// apply default schematype path selections</span>
  <span class="keyword">this</span>._applyPaths();

  <span class="keyword">var</span> self = <span class="keyword">this</span>
    , castQuery = <span class="keyword">this</span>._conditions
    , options = <span class="keyword">this</span>._optionsForExec(model)
    , fields = utils.clone(<span class="keyword">this</span>._fields)

  options.fields = <span class="keyword">this</span>._castFields(fields);
  <span class="keyword">if</span> (options.fields <span class="keyword">instanceof</span> Error) {
    promise.error(options.fields);
    <span class="keyword">return</span> <span class="keyword">this</span>;
  }

  model.collection.findOne(castQuery, options, tick(<span class="function"><span class="keyword">function</span> <span class="params">(err, doc)</span> {</span>
    <span class="keyword">if</span> (err) <span class="keyword">return</span> promise.error(err);
    <span class="keyword">if</span> (!doc) <span class="keyword">return</span> promise.complete(<span class="literal">null</span>);

    <span class="keyword">if</span> (<span class="literal">true</span> === options.lean) <span class="keyword">return</span> promise.complete(doc);

    <span class="keyword">var</span> casted = <span class="keyword">new</span> model(<span class="literal">undefined</span>, fields, <span class="literal">true</span>);
    casted.init(doc, self, <span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
      <span class="keyword">if</span> (err) <span class="keyword">return</span> promise.error(err);
      promise.complete(casted);
    });
  }));

  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>callback</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="description"><h4>Example</h4>

<pre><code>Kitten.where(<span class="string">'color'</span>, <span class="string">'white'</span>).findOne(<span class="function"><span class="keyword">function</span> <span class="params">(err, kitten)</span> {</span>
  <span class="keyword">if</span> (err) <span class="keyword">return</span> handleError(err);

  <span class="comment">// kitten may be null if no document matched</span>
  <span class="keyword">if</span> (kitten) {
    ...
  }
})</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-count"><a href="#query_Query-count">Query#count(<code>callback</code>)</a></h3><p>Exectues the query as a count() operation.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.count = <span class="function"><span class="keyword">function</span> <span class="params">(callback)</span> {</span>
  <span class="keyword">this</span>.op = <span class="string">'count'</span>;
  <span class="keyword">var</span> model = <span class="keyword">this</span>.model;

  <span class="keyword">try</span> {
    <span class="keyword">this</span>.cast(model);
  } <span class="keyword">catch</span> (err) {
    <span class="keyword">return</span> callback(err);
  }

  <span class="keyword">var</span> castQuery = <span class="keyword">this</span>._conditions;
  model.collection.count(castQuery, tick(callback));

  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>callback</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Count" title="mongodb">mongodb</a></li></ul></div><div class="description"><h4>Example</h4>

<pre><code>Kitten.where(<span class="string">'color'</span>, <span class="string">'black'</span>).count(<span class="function"><span class="keyword">function</span> <span class="params">(err, count)</span> {</span>
  <span class="keyword">if</span> (err) <span class="keyword">return</span> handleError(err);
  console.log(<span class="string">'there are %d black kittens'</span>, count);
})</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-distinct"><a href="#query_Query-distinct">Query#distinct(<code>field</code>, <code>callback</code>)</a></h3><p>Executes this query as a distict() operation.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.distinct = <span class="function"><span class="keyword">function</span> <span class="params">(field, callback)</span> {</span>
  <span class="keyword">this</span>.op = <span class="string">'distinct'</span>;
  <span class="keyword">var</span> model = <span class="keyword">this</span>.model;

  <span class="keyword">try</span> {
    <span class="keyword">this</span>.cast(model);
  } <span class="keyword">catch</span> (err) {
    <span class="keyword">return</span> callback(err);
  }

  <span class="keyword">var</span> castQuery = <span class="keyword">this</span>._conditions;
  model.collection.distinct(field, castQuery, tick(callback));

  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>field</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>callback</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/Aggregation#Aggregation-Distinct" title="mongodb">mongodb</a></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="query_Query-update"><a href="#query_Query-update">Query#update(<code>doc</code>, <code>callback</code>)</a></h3><p>Executes this query as an update() operation.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.update = <span class="function"><span class="keyword">function</span> <span class="title">update</span> <span class="params">(doc, callback)</span> {</span>
  <span class="keyword">this</span>.op = <span class="string">'update'</span>;
  <span class="keyword">this</span>._updateArg = doc;

  <span class="keyword">var</span> model = <span class="keyword">this</span>.model
    , options = <span class="keyword">this</span>._optionsForExec(model)
    , fn = <span class="string">'function'</span> == <span class="keyword">typeof</span> callback
    , castedQuery
    , castedDoc

  castedQuery = castQuery(<span class="keyword">this</span>);
  <span class="keyword">if</span> (castedQuery <span class="keyword">instanceof</span> Error) {
    <span class="keyword">if</span> (fn) {
      process.nextTick(callback.bind(<span class="literal">null</span>, castedQuery));
      <span class="keyword">return</span> <span class="keyword">this</span>;
    }
    <span class="keyword">throw</span> castedQuery;
  }

  castedDoc = castDoc(<span class="keyword">this</span>);
  <span class="keyword">if</span> (!castedDoc) {
    fn &amp;&amp; process.nextTick(callback.bind(<span class="literal">null</span>, <span class="literal">null</span>, <span class="number">0</span>));
    <span class="keyword">return</span> <span class="keyword">this</span>;
  }

  <span class="keyword">if</span> (castedDoc <span class="keyword">instanceof</span> Error) {
    <span class="keyword">if</span> (fn) {
      process.nextTick(callback.bind(<span class="literal">null</span>, castedDoc));
      <span class="keyword">return</span> <span class="keyword">this</span>;
    }
    <span class="keyword">throw</span> castedDoc;
  }

  <span class="keyword">if</span> (!fn) {
    <span class="keyword">delete</span> options.safe;
  }

  model.collection.update(castedQuery, castedDoc, options, tick(callback));
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>doc</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>the update conditions</span></li><li><code>callback</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="description"><p><em>All paths passed that are not $atomic operations will become $set ops so we retain backwards compatibility.</em></p>

<h4>Example</h4>

<pre><code>Model.update({..}, { title: <span class="string">'remove words'</span> }, ...)</code></pre>

<p>becomes</p>

<pre><code>Model.update({..}, { $set: { title: <span class="string">'remove words'</span> }}, ...)</code></pre>

<h4>Note</h4>

<p>Passing an empty object <code>{}</code> as the doc will result in a no-op. The update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting the collection.</p></div><hr class=""></div><div class="item method private"><h3 id="query_Query-_castUpdate"><a href="#query_Query-_castUpdate">Query#_castUpdate(<code>obj</code>)</a></h3><p>Casts obj for an update command.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype._castUpdate = <span class="function"><span class="keyword">function</span> <span class="title">_castUpdate</span> <span class="params">(obj)</span> {</span>
  <span class="keyword">var</span> ops = Object.keys(obj)
    , i = ops.length
    , ret = {}
    , hasKeys
    , val

  <span class="keyword">while</span> (i--) {
    <span class="keyword">var</span> op = ops[i];
    <span class="keyword">if</span> (<span class="string">'$'</span> !== op[<span class="number">0</span>]) {
      <span class="comment">// fix up $set sugar</span>
      <span class="keyword">if</span> (!ret.$set) {
        <span class="keyword">if</span> (obj.$set) {
          ret.$set = obj.$set;
        } <span class="keyword">else</span> {
          ret.$set = {};
        }
      }
      ret.$set[op] = obj[op];
      ops.splice(i, <span class="number">1</span>);
      <span class="keyword">if</span> (!~ops.indexOf(<span class="string">'$set'</span>)) ops.push(<span class="string">'$set'</span>);
    } <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">'$set'</span> === op) {
      <span class="keyword">if</span> (!ret.$set) {
        ret[op] = obj[op];
      }
    } <span class="keyword">else</span> {
      ret[op] = obj[op];
    }
  }

  <span class="comment">// cast each value</span>
  i = ops.length;

  <span class="keyword">while</span> (i--) {
    op = ops[i];
    val = ret[op];
    <span class="keyword">if</span> (<span class="string">'Object'</span> === val.constructor.name) {
      hasKeys |= <span class="keyword">this</span>._walkUpdatePath(val, op);
    } <span class="keyword">else</span> {
      <span class="keyword">var</span> msg = <span class="string">'Invalid atomic update value for '</span> + op + <span class="string">'. '</span>
              + <span class="string">'Expected an object, received '</span> + <span class="keyword">typeof</span> val;
      <span class="keyword">throw</span> <span class="keyword">new</span> Error(msg);
    }
  }

  <span class="keyword">return</span> hasKeys &amp;&amp; ret;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>obj</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>obj after casting its values</span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="query_Query-_walkUpdatePath"><a href="#query_Query-_walkUpdatePath">Query#_walkUpdatePath(<code>obj</code>, <code>op</code>, <code>pref</code>)</a></h3><p>Walk each path of obj and cast its values<br />according to its schema.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype._walkUpdatePath = <span class="function"><span class="keyword">function</span> <span class="title">_walkUpdatePath</span> <span class="params">(obj, op, pref)</span> {</span>
  <span class="keyword">var</span> strict = <span class="keyword">this</span>.model.schema.options.strict
    , prefix = pref ? pref + <span class="string">'.'</span> : <span class="string">''</span>
    , keys = Object.keys(obj)
    , i = keys.length
    , hasKeys = <span class="literal">false</span>
    , schema
    , key
    , val

  <span class="keyword">while</span> (i--) {
    key = keys[i];
    val = obj[key];

    <span class="keyword">if</span> (val &amp;&amp; <span class="string">'Object'</span> === val.constructor.name) {
      <span class="comment">// watch for embedded doc schemas</span>
      schema = <span class="keyword">this</span>._getSchema(prefix + key);
      <span class="keyword">if</span> (schema &amp;&amp; schema.caster &amp;&amp; op <span class="keyword">in</span> castOps) {
        <span class="comment">// embedded doc schema</span>

        <span class="keyword">if</span> (strict &amp;&amp; !schema) {
          <span class="comment">// path is not in our strict schema</span>
          <span class="keyword">if</span> (<span class="string">'throw'</span> == strict) {
            <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">'Field `'</span> + key + <span class="string">'` is not in schema.'</span>);
          } <span class="keyword">else</span> {
            <span class="comment">// ignore paths not specified in schema</span>
            <span class="keyword">delete</span> obj[key];
          }
        } <span class="keyword">else</span> {
          hasKeys = <span class="literal">true</span>;
          <span class="keyword">if</span> (<span class="string">'$each'</span> <span class="keyword">in</span> val) {
            obj[key] = {
                $each: <span class="keyword">this</span>._castUpdateVal(schema, val.$each, op)
            }
          } <span class="keyword">else</span> {
            obj[key] = <span class="keyword">this</span>._castUpdateVal(schema, val, op);
          }
        }
      } <span class="keyword">else</span> {
        hasKeys |= <span class="keyword">this</span>._walkUpdatePath(val, op, prefix + key);
      }
    } <span class="keyword">else</span> {
      schema = <span class="string">'$each'</span> === key
        ? <span class="keyword">this</span>._getSchema(pref)
        : <span class="keyword">this</span>._getSchema(prefix + key);

      <span class="keyword">var</span> skip = strict &amp;&amp;
                 !schema &amp;&amp;
                 !<span class="regexp">/real|nested/</span>.test(<span class="keyword">this</span>.model.schema.pathType(prefix + key));

      <span class="keyword">if</span> (skip) {
        <span class="keyword">if</span> (<span class="string">'throw'</span> == strict) {
          <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">'Field `'</span> + prefix + key + <span class="string">'` is not in schema.'</span>);
        } <span class="keyword">else</span> {
          <span class="keyword">delete</span> obj[key];
        }
      } <span class="keyword">else</span> {
        hasKeys = <span class="literal">true</span>;
        obj[key] = <span class="keyword">this</span>._castUpdateVal(schema, val, op, key);
      }
    }
  }
  <span class="keyword">return</span> hasKeys;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>obj</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>- part of a query</span></li><li><code>op</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>- the atomic operator ($pull, $set, etc)</span></li><li><code>pref</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>- path prefix (internal only)</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#Bool">Bool</a>&gt; </span><span>true if this path has keys to update</span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="query_Query-_castUpdateVal"><a href="#query_Query-_castUpdateVal">Query#_castUpdateVal(<code>schema</code>, <code>val</code>, <code>op</code>, <code>[$conditional]</code>)</a></h3><p>Casts <code>val</code> according to <code>schema</code> and atomic <code>op</code>.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype._castUpdateVal = <span class="function"><span class="keyword">function</span> <span class="title">_castUpdateVal</span> <span class="params">(schema, val, op, $conditional)</span> {</span>
  <span class="keyword">if</span> (!schema) {
    <span class="comment">// non-existing schema path</span>
    <span class="keyword">return</span> op <span class="keyword">in</span> numberOps
      ? Number(val)
      : val
  }

  <span class="keyword">if</span> (schema.caster &amp;&amp; op <span class="keyword">in</span> castOps &amp;&amp;
    (<span class="string">'Object'</span> === val.constructor.name || Array.isArray(val))) {
    <span class="comment">// Cast values for ops that add data to MongoDB.</span>
    <span class="comment">// Ensures embedded documents get ObjectIds etc.</span>
    <span class="keyword">var</span> tmp = schema.cast(val);

    <span class="keyword">if</span> (Array.isArray(val)) {
      val = tmp;
    } <span class="keyword">else</span> {
      val = tmp[<span class="number">0</span>];
    }
  }

  <span class="keyword">if</span> (op <span class="keyword">in</span> numberOps) <span class="keyword">return</span> Number(val);
  <span class="keyword">if</span> (<span class="regexp">/^\$/</span>.test($conditional)) <span class="keyword">return</span> schema.castForQuery($conditional, val);
  <span class="keyword">return</span> schema.castForQuery(val)
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>schema</code><span class="types"> &lt;<a href="#schema_Schema">Schema</a>&gt; </span><span></span></li><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>op</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>- the atomic operator ($pull, $set, etc)</span></li><li><code>[$conditional]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="query_Query-_getSchema"><a href="#query_Query-_getSchema">Query#_getSchema(<code>path</code>)</a></h3><p>Finds the schema for <code>path</code>. This is different than<br />calling <code>schema.path</code> as it also resolves paths with<br />positional selectors (something.$.another.$.path).</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype._getSchema = <span class="function"><span class="keyword">function</span> <span class="title">_getSchema</span> <span class="params">(path)</span> {</span>
  <span class="keyword">var</span> schema = <span class="keyword">this</span>.model.schema
    , pathschema = schema.path(path);

  <span class="keyword">if</span> (pathschema)
    <span class="keyword">return</span> pathschema;

  <span class="comment">// look for arrays</span>
  <span class="keyword">return</span> (<span class="function"><span class="keyword">function</span> <span class="title">search</span> <span class="params">(parts, schema)</span> {</span>
    <span class="keyword">var</span> p = parts.length + <span class="number">1</span>
      , foundschema
      , trypath

    <span class="keyword">while</span> (p--) {
      trypath = parts.slice(<span class="number">0</span>, p).join(<span class="string">'.'</span>);
      foundschema = schema.path(trypath);
      <span class="keyword">if</span> (foundschema) {
        <span class="keyword">if</span> (foundschema.caster) {

          <span class="comment">// array of Mixed?</span>
          <span class="keyword">if</span> (foundschema.caster <span class="keyword">instanceof</span> Types.Mixed) {
            <span class="keyword">return</span> foundschema.caster;
          }

          <span class="comment">// Now that we found the array, we need to check if there</span>
          <span class="comment">// are remaining document paths to look up for casting.</span>
          <span class="comment">// Also we need to handle array.$.path since schema.path</span>
          <span class="comment">// doesn't work for that.</span>
          <span class="keyword">if</span> (p !== parts.length) {
            <span class="keyword">if</span> (<span class="string">'$'</span> === parts[p]) {
              <span class="comment">// comments.$.comments.$.title</span>
              <span class="keyword">return</span> search(parts.slice(p+<span class="number">1</span>), foundschema.schema);
            } <span class="keyword">else</span> {
              <span class="comment">// this is the last path of the selector</span>
              <span class="keyword">return</span> search(parts.slice(p), foundschema.schema);
            }
          }
        }
        <span class="keyword">return</span> foundschema;
      }
    }
  })(path.split(<span class="string">'.'</span>), schema)
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="query_Query-_castFields"><a href="#query_Query-_castFields">Query#_castFields(<code>fields</code>)</a></h3><p>Casts selected field arguments for field selection with mongo 2.2</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype._castFields = <span class="function"><span class="keyword">function</span> <span class="title">_castFields</span> <span class="params">(fields)</span> {</span>
  <span class="keyword">var</span> selected
    , elemMatchKeys
    , keys
    , key
    , out
    , i

  <span class="keyword">if</span> (fields) {
    keys = Object.keys(fields);
    elemMatchKeys = [];
    i = keys.length;

    <span class="comment">// collect $elemMatch args</span>
    <span class="keyword">while</span> (i--) {
      key = keys[i];
      <span class="keyword">if</span> (fields[key].$elemMatch) {
        selected || (selected = {});
        selected[key] = fields[key];
        elemMatchKeys.push(key);
      }
    }
  }

  <span class="keyword">if</span> (selected) {
    <span class="comment">// they passed $elemMatch, cast em</span>
    <span class="keyword">try</span> {
      out = <span class="keyword">this</span>.cast(<span class="keyword">this</span>.model, selected);
    } <span class="keyword">catch</span> (err) {
      <span class="keyword">return</span> err;
    }

    <span class="comment">// apply the casted field args</span>
    i = elemMatchKeys.length;
    <span class="keyword">while</span> (i--) {
      key = elemMatchKeys[i];
      fields[key] = out[key];
    }
  }

  <span class="keyword">return</span> fields;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>fields</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="https://github.com/LearnBoost/mongoose/issues/1091">https://github.com/LearnBoost/mongoose/issues/1091</a></li><li><a href="http://docs.mongodb.org/manual/reference/projection/elemMatch/">http://docs.mongodb.org/manual/reference/projection/elemMatch/</a></li></ul></div><div class="description"><pre><code>query.select({ ids: { $elemMatch: { $<span class="keyword">in</span>: [hexString] }})</code></pre></div><hr class="private"></div><div class="item method public"><h3 id="query_Query-remove"><a href="#query_Query-remove">Query#remove(<code>callback</code>)</a></h3><p>Executes this query as a remove() operation.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.remove = <span class="function"><span class="keyword">function</span> <span class="params">(callback)</span> {</span>
  <span class="keyword">this</span>.op = <span class="string">'remove'</span>;

  <span class="keyword">var</span> model = <span class="keyword">this</span>.model
    , options = <span class="keyword">this</span>._optionsForExec(model)
    , cb = <span class="string">'function'</span> == <span class="keyword">typeof</span> callback

  <span class="keyword">try</span> {
    <span class="keyword">this</span>.cast(model);
  } <span class="keyword">catch</span> (err) {
    <span class="keyword">if</span> (cb) <span class="keyword">return</span> callback(err);
    <span class="keyword">throw</span> err;
  }

  <span class="keyword">if</span> (!cb) {
    <span class="keyword">delete</span> options.safe;
  }

  <span class="keyword">var</span> castQuery = <span class="keyword">this</span>._conditions;
  model.collection.remove(castQuery, options, tick(callback));
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>callback</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="description"><h4>Example</h4>

<pre><code>Cassette.where(<span class="string">'artist'</span>).equals(<span class="string">'Anne Murray'</span>).remove(callback)</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-findOneAndUpdate"><a href="#query_Query-findOneAndUpdate">Query#findOneAndUpdate(<code>[query]</code>, <code>[doc]</code>, <code>[options]</code>, <code>[callback]</code>)</a></h3><p>Issues a mongodb <a href="http://www.mongodb.org/display/DOCS/findAndModify+Command">findAndModify</a> update command.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.findOneAndUpdate = <span class="function"><span class="keyword">function</span> <span class="params">(query, doc, options, callback)</span> {</span>
  <span class="keyword">this</span>.op = <span class="string">'findOneAndUpdate'</span>;

  <span class="keyword">switch</span> (arguments.length) {
    <span class="keyword">case</span> <span class="number">3</span>:
      <span class="keyword">if</span> (<span class="string">'function'</span> == <span class="keyword">typeof</span> options)
        callback = options, options = {};
      <span class="keyword">break</span>;
    <span class="keyword">case</span> <span class="number">2</span>:
      <span class="keyword">if</span> (<span class="string">'function'</span> == <span class="keyword">typeof</span> doc) {
        callback = doc;
        doc = query;
        query = <span class="literal">undefined</span>;
      }
      options = <span class="literal">undefined</span>;
      <span class="keyword">break</span>;
    <span class="keyword">case</span> <span class="number">1</span>:
      <span class="keyword">if</span> (<span class="string">'function'</span> == <span class="keyword">typeof</span> query) {
        callback = query;
        query = options = doc = <span class="literal">undefined</span>;
      } <span class="keyword">else</span> {
        doc = query;
        query = options = <span class="literal">undefined</span>;
      }
  }

  <span class="comment">// apply query</span>
  <span class="keyword">if</span> (query) {
    <span class="keyword">if</span> (<span class="string">'Object'</span> === query.constructor.name) {
      merge(<span class="keyword">this</span>._conditions, query);
    } <span class="keyword">else</span> <span class="keyword">if</span> (query <span class="keyword">instanceof</span> Query) {
      merge(<span class="keyword">this</span>._conditions, query._conditions);
    } <span class="keyword">else</span> <span class="keyword">if</span> (query <span class="keyword">instanceof</span> Document) {
      merge(<span class="keyword">this</span>._conditions, query.toObject());
    }
  }

  <span class="comment">// apply doc</span>
  <span class="keyword">if</span> (doc) {
    merge(<span class="keyword">this</span>._updateArg, doc);
  }

  <span class="comment">// apply options</span>
  options &amp;&amp; <span class="keyword">this</span>.setOptions(options);

  <span class="keyword">if</span> (!callback) <span class="keyword">return</span> <span class="keyword">this</span>;

  <span class="keyword">return</span> <span class="keyword">this</span>._findAndModify(<span class="string">'update'</span>, callback);
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>[query]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[doc]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[options]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[callback]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/findAndModify+Command" title="mongodb">mongodb</a></li></ul></div><div class="description"><p>Finds a matching document, updates it according to the <code>update</code> arg, passing any <code>options</code>, and returns the found document (if any) to the callback. The query executes immediately if <code>callback</code> is passed else a Query object is returned.</p>

<h4>Available options</h4>

<ul>
<li><code>new</code>: bool - true to return the modified document rather than the original. defaults to true</li>
<li><code>upsert</code>: bool - creates the object if it doesn't exist. defaults to false.</li>
<li><code>sort</code>: if multiple docs are found by the conditions, sets the sort order to choose which doc to update</li>
</ul>

<h4>Examples</h4>

<pre><code>query.findOneAndUpdate(conditions, update, options, callback) <span class="comment">// executes</span>
query.findOneAndUpdate(conditions, update, options)  <span class="comment">// returns Query</span>
query.findOneAndUpdate(conditions, update, callback) <span class="comment">// executes</span>
query.findOneAndUpdate(conditions, update)           <span class="comment">// returns Query</span>
query.findOneAndUpdate(callback)                     <span class="comment">// executes</span>
query.findOneAndUpdate()                             <span class="comment">// returns Query</span></code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-findOneAndRemove"><a href="#query_Query-findOneAndRemove">Query#findOneAndRemove(<code>[conditions]</code>, <code>[options]</code>, <code>[callback]</code>)</a></h3><p>Issues a mongodb <a href="http://www.mongodb.org/display/DOCS/findAndModify+Command">findAndModify</a> remove command.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.findOneAndRemove = <span class="function"><span class="keyword">function</span> <span class="params">(conditions, options, callback)</span> {</span>
  <span class="keyword">this</span>.op = <span class="string">'findOneAndRemove'</span>;

  <span class="keyword">if</span> (<span class="string">'function'</span> == <span class="keyword">typeof</span> options) {
    callback = options;
    options = <span class="literal">undefined</span>;
  } <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">'function'</span> == <span class="keyword">typeof</span> conditions) {
    callback = conditions;
    conditions = <span class="literal">undefined</span>;
  }

  <span class="comment">// apply conditions</span>
  <span class="keyword">if</span> (conditions) {
    <span class="keyword">if</span> (<span class="string">'Object'</span> === conditions.constructor.name) {
      merge(<span class="keyword">this</span>._conditions, conditions);
    } <span class="keyword">else</span> <span class="keyword">if</span> (conditions <span class="keyword">instanceof</span> Query) {
      merge(<span class="keyword">this</span>._conditions, conditions._conditions);
    } <span class="keyword">else</span> <span class="keyword">if</span> (conditions <span class="keyword">instanceof</span> Document) {
      merge(<span class="keyword">this</span>._conditions, conditions.toObject());
    }
  }

  <span class="comment">// apply options</span>
  options &amp;&amp; <span class="keyword">this</span>.setOptions(options);

  <span class="keyword">if</span> (!callback) <span class="keyword">return</span> <span class="keyword">this</span>;

  <span class="keyword">return</span> <span class="keyword">this</span>._findAndModify(<span class="string">'remove'</span>, callback);
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>[conditions]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[options]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[callback]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/findAndModify+Command" title="mongodb">mongodb</a></li></ul></div><div class="description"><p>Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if <code>callback</code> is passed else a Query object is returned.</p>

<h4>Available options</h4>

<ul>
<li><code>sort</code>: if multiple docs are found by the conditions, sets the sort order to choose which doc to update</li>
</ul>

<h4>Examples</h4>

<pre><code>A.where().findOneAndRemove(conditions, options, callback) <span class="comment">// executes</span>
A.where().findOneAndRemove(conditions, options)  <span class="comment">// return Query</span>
A.where().findOneAndRemove(conditions, callback) <span class="comment">// executes</span>
A.where().findOneAndRemove(conditions) <span class="comment">// returns Query</span>
A.where().findOneAndRemove(callback)   <span class="comment">// executes</span>
A.where().findOneAndRemove()           <span class="comment">// returns Query</span></code></pre></div><hr class=""></div><div class="item method private"><h3 id="query_Query-_findAndModify"><a href="#query_Query-_findAndModify">Query#_findAndModify(<code>type</code>, <code>callback</code>)</a></h3><p>_findAndModify</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype._findAndModify = <span class="function"><span class="keyword">function</span> <span class="params">(type, callback)</span> {</span>
  <span class="keyword">var</span> model = <span class="keyword">this</span>.model
    , promise = <span class="keyword">new</span> Promise(callback)
    , self = <span class="keyword">this</span>
    , castedQuery
    , castedDoc
    , fields
    , sort
    , opts

  castedQuery = castQuery(<span class="keyword">this</span>);
  <span class="keyword">if</span> (castedQuery <span class="keyword">instanceof</span> Error) {
    process.nextTick(promise.error.bind(promise, castedQuery));
    <span class="keyword">return</span> promise;
  }

  opts = <span class="keyword">this</span>._optionsForExec(model);

  <span class="keyword">if</span> (<span class="string">'remove'</span> == type) {
    opts.remove = <span class="literal">true</span>;
  } <span class="keyword">else</span> {
    <span class="keyword">if</span> (!(<span class="string">'new'</span> <span class="keyword">in</span> opts)) opts.<span class="keyword">new</span> = <span class="literal">true</span>;
    <span class="keyword">if</span> (!(<span class="string">'upsert'</span> <span class="keyword">in</span> opts)) opts.upsert = <span class="literal">false</span>;

    castedDoc = castDoc(<span class="keyword">this</span>);
    <span class="keyword">if</span> (!castedDoc) {
      <span class="keyword">if</span> (opts.upsert) {
        <span class="comment">// still need to do the upsert to empty doc</span>
        castedDoc = { $set: {} };
      } <span class="keyword">else</span> {
        <span class="keyword">return</span> <span class="keyword">this</span>.findOne(callback);
      }
    } <span class="keyword">else</span> <span class="keyword">if</span> (castedDoc <span class="keyword">instanceof</span> Error) {
      process.nextTick(promise.error.bind(promise, castedDoc));
      <span class="keyword">return</span> promise;
    }
  }

  <span class="keyword">if</span> (<span class="keyword">this</span>._fields) {
    fields = utils.clone(<span class="keyword">this</span>._fields)
    opts.fields = <span class="keyword">this</span>._castFields(fields);
    <span class="keyword">if</span> (opts.fields <span class="keyword">instanceof</span> Error) {
      process.nextTick(promise.error.bind(promise, opts.fields));
      <span class="keyword">return</span> promise;
    }
  }

  <span class="comment">// the driver needs a default</span>
  sort = opts.sort || [];

  model
  .collection
  .findAndModify(castedQuery, sort, castedDoc, opts, tick(<span class="function"><span class="keyword">function</span> <span class="params">(err, doc)</span> {</span>
    <span class="keyword">if</span> (err) <span class="keyword">return</span> promise.error(err);
    <span class="keyword">if</span> (!doc) <span class="keyword">return</span> promise.complete(<span class="literal">null</span>);

    <span class="keyword">if</span> (<span class="literal">true</span> === opts.lean) {
      <span class="keyword">return</span> promise.complete(doc);
    }

    <span class="keyword">var</span> casted = <span class="keyword">new</span> model(<span class="literal">undefined</span>, fields, <span class="literal">true</span>);
    casted.init(doc, self, <span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
      <span class="keyword">if</span> (err) <span class="keyword">return</span> promise.error(err);
      promise.complete(casted);
    });
  }));

  <span class="keyword">return</span> promise;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>type</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>- either &quot;remove&quot; or &quot;update&quot;</span></li><li><code>callback</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="query_Query-populate"><a href="#query_Query-populate">Query#populate(<code>path</code>, <code>[fields]</code>, <code>[model]</code>, <code>[conditions]</code>, <code>[options]</code>)</a></h3><p>Specifies paths which should be populated with other documents.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.populate = <span class="function"><span class="keyword">function</span> <span class="params">(path, fields, model, conditions, options)</span> {</span>
  <span class="keyword">if</span> (<span class="string">'string'</span> !== <span class="keyword">typeof</span> model) {
    options = conditions;
    conditions = model;
    model = <span class="literal">undefined</span>;
  }
  <span class="comment">// The order of fields/conditions args is opposite Model.find but</span>
  <span class="comment">// necessary to keep backward compatibility (fields could be</span>
  <span class="comment">// an array, string, or object literal).</span>
  <span class="keyword">this</span>.options.populate[path] =
    <span class="keyword">new</span> PopulateOptions(fields, conditions, options, model);

  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>[fields]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>[model]</code><span class="types"> &lt;<a href="#model_Model">Model</a>&gt; </span><span></span></li><li><code>[conditions]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[options]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="./populate.html" title="population">population</a></li><li><a href="#query_Query-select" title="Query#select">Query#select</a></li></ul></div><div class="description"><p>Paths are populated after the query executes and a response is received. A separate query is then executed for each path specified for population. After a response for each query has also been returned, the results are passed to the callback.</p>

<h4>Example:</h4>

<pre><code>Kitten.findOne().populate(<span class="string">'owner'</span>).exec(<span class="function"><span class="keyword">function</span> <span class="params">(err, kitten)</span> {</span>
  console.log(kitten.owner.name) <span class="comment">// Max</span>
})</code></pre></div><hr class=""></div><div class="item method public"><h3 id="query_Query-stream"><a href="#query_Query-stream">Query#stream()</a></h3><p>Returns a stream interface</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Query.prototype.stream = <span class="function"><span class="keyword">function</span> <span class="title">stream</span> <span class="params">()</span> {</span>
  <span class="keyword">return</span> <span class="keyword">new</span> QueryStream(<span class="keyword">this</span>);
}

<span class="comment">// helpers</span></code></pre></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#querystream_QueryStream">QueryStream</a>&gt; </span><span></span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="#querystream_QueryStream" title="QueryStream">QueryStream</a></li></ul></div><div class="description"><h4>Example</h4>

<pre><code><span class="comment">// follows the nodejs stream api</span>
Thing.find({ name: <span class="regexp">/^hello/</span> }).stream().pipe(res)

<span class="comment">// manual streaming</span>
<span class="keyword">var</span> stream = Thing.find({ name: <span class="regexp">/^hello/</span> }).stream();

stream.on(<span class="string">'data'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(doc)</span> {</span>
  <span class="comment">// do something with the mongoose document</span>
}).on(<span class="string">'error'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
  <span class="comment">// handle the error</span>
}).on(<span class="string">'close'</span>, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="comment">// the stream is closed</span>
});</code></pre></div><hr class=""></div><div class="item property public"><h3 id="query_Query-within"><a href="#query_Query-within">Query#<span>within</span></a></h3><p>Syntax sugar for expressive queries.</p>

<h4>Example</h4>

<pre><code>query.within.box()
query.within.center()</code></pre><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span>this</span></li></ul></div><hr class=""></div></li><li class="module "><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/querystream.js" id="querystream-js">querystream.js</a><div class="item method public"><h3 id="querystream_QueryStream"><a href="#querystream_QueryStream">QueryStream(<code>query</code>)</a></h3><p>Provides a <a href="http://nodejs.org/api/stream.html#stream_readable_stream">ReadStream</a> interface for Queries.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">QueryStream</span> <span class="params">(query)</span> {</span>
  Stream.call(<span class="keyword">this</span>);

  <span class="keyword">this</span>.query = query;
  <span class="keyword">this</span>.readable = <span class="literal">true</span>;
  <span class="keyword">this</span>.paused = <span class="literal">false</span>;
  <span class="keyword">this</span>._cursor = <span class="literal">null</span>;
  <span class="keyword">this</span>._destroyed = <span class="literal">null</span>;
  <span class="keyword">this</span>._fields = <span class="literal">null</span>;
  <span class="keyword">this</span>._buffer = <span class="literal">null</span>;
  <span class="keyword">this</span>._inline = T_INIT;

  <span class="comment">// give time to hook up events</span>
  <span class="keyword">var</span> self = <span class="keyword">this</span>;
  process.nextTick(<span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
    self._init();
  });
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>query</code><span class="types"> &lt;<a href="#query-js">Query</a>&gt; </span><span></span></li></ul></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="http://nodejs.org/api/stream.html" title="NodeJS Stream">NodeJS Stream</a></li></ul></div><div class="events"><h4>Events:</h4><ul><li><p><code>data</code>: emits a single Mongoose document</p></li><li><p><code>error</code>: emits when an error occurs during streaming. This will emit <em>before</em> the <code>close</code> event.</p></li><li><p><code>close</code>: emits when the stream reaches the end of the cursor or an error occurs, or the stream is manually <code>destroy</code>ed. After this event, no more events are emitted.</p></li></ul></div><div class="description"><pre><code><span class="keyword">var</span> stream = Model.find().stream();

stream.on(<span class="string">'data'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(doc)</span> {</span>
  <span class="comment">// do something with the mongoose document</span>
}).on(<span class="string">'error'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
  <span class="comment">// handle the error</span>
}).on(<span class="string">'close'</span>, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="comment">// the stream is closed</span>
});</code></pre>

<p>The stream interface allows us to simply "plug-in" to other Node streams such as http responses and write streams so everything "just works" out of the box.</p>

<pre><code>Model.where(<span class="string">'created'</span>).gte(twoWeeksAgo).stream().pipe(writeStream);</code></pre></div><hr class=""></div><div class="item method private"><h3 id="querystream_QueryStream-_init"><a href="#querystream_QueryStream-_init">QueryStream#_init()</a></h3><p>Initializes the query.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">QueryStream.prototype._init = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">if</span> (<span class="keyword">this</span>._destroyed) <span class="keyword">return</span>;

  <span class="keyword">var</span> query = <span class="keyword">this</span>.query
    , model = query.model
    , options = query._optionsForExec(model)
    , self = <span class="keyword">this</span>

  <span class="keyword">try</span> {
    query.cast(model);
  } <span class="keyword">catch</span> (err) {
    <span class="keyword">return</span> self.destroy(err);
  }

  self._fields = utils.clone(query._fields);
  options.fields = query._castFields(self._fields);

  model.collection.find(query._conditions, options, <span class="function"><span class="keyword">function</span> <span class="params">(err, cursor)</span> {</span>
    <span class="keyword">if</span> (err) <span class="keyword">return</span> self.destroy(err);
    self._cursor = cursor;
    self._next();
  });
}</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="querystream_QueryStream-_next"><a href="#querystream_QueryStream-_next">QueryStream#_next()</a></h3><p>Trampoline for pulling the next doc from cursor.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">QueryStream.prototype._next = <span class="function"><span class="keyword">function</span> <span class="title">_next</span> <span class="params">()</span> {</span>
  <span class="keyword">if</span> (<span class="keyword">this</span>.paused || <span class="keyword">this</span>._destroyed) <span class="keyword">return</span>;

  <span class="keyword">if</span> (<span class="keyword">this</span>._buffer &amp;&amp; <span class="keyword">this</span>._buffer.length) {
    <span class="keyword">var</span> arg;
    <span class="keyword">while</span> (!<span class="keyword">this</span>.paused &amp;&amp; !<span class="keyword">this</span>._destroyed &amp;&amp; (arg = <span class="keyword">this</span>._buffer.shift())) {
      <span class="keyword">this</span>._onNextObject.apply(<span class="keyword">this</span>, arg);
    }
  }

  <span class="comment">// account for possible nextObjects calling user code</span>
  <span class="keyword">if</span> (<span class="keyword">this</span>.paused || <span class="keyword">this</span>._destroyed) <span class="keyword">return</span>;

  <span class="comment">// avoid stack overflows with large result sets.</span>
  <span class="comment">// trampoline instead of recursion.</span>
  <span class="keyword">var</span> fn;
  <span class="keyword">while</span> (<span class="keyword">this</span>.__next()) {}
}</code></pre></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="#querystream_QueryStream-__next" title="QueryStream#__next">QueryStream#__next</a></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="querystream_QueryStream-__next"><a href="#querystream_QueryStream-__next">QueryStream#__next()</a></h3><p>Pulls the next doc from the cursor.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">QueryStream.prototype.__next = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">if</span> (<span class="keyword">this</span>.paused || <span class="keyword">this</span>._destroyed) <span class="keyword">return</span>;

  <span class="keyword">var</span> self = <span class="keyword">this</span>;
  self._inline = T_INIT;

  self._cursor.nextObject(<span class="function"><span class="keyword">function</span> <span class="title">cursorcb</span> <span class="params">(err, doc)</span> {</span>
    self._onNextObject(err, doc);
  });

  <span class="comment">// if onNextObject() was already called in this tick</span>
  <span class="comment">// return ourselves to the trampoline.</span>
  <span class="keyword">if</span> (T_CONT === <span class="keyword">this</span>._inline) {
    <span class="keyword">return</span> <span class="literal">true</span>;
  } <span class="keyword">else</span> {
    <span class="comment">// onNextObject() hasn't fired yet. tell onNextObject</span>
    <span class="comment">// that its ok to call _next b/c we are not within</span>
    <span class="comment">// the trampoline anymore.</span>
    <span class="keyword">this</span>._inline = T_IDLE;
  }
}</code></pre></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="#querystream_QueryStream-_next" title="QueryStream#_next">QueryStream#_next</a></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="querystream_QueryStream-_onNextObject"><a href="#querystream_QueryStream-_onNextObject">QueryStream#_onNextObject(<code>err</code>, <code>doc</code>)</a></h3><p>Transforms raw <code>doc</code>s returned from the cursor into a model instance.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">QueryStream.prototype._onNextObject = <span class="function"><span class="keyword">function</span> <span class="title">_onNextObject</span> <span class="params">(err, doc)</span> {</span>
  <span class="keyword">if</span> (<span class="keyword">this</span>._destroyed) <span class="keyword">return</span>;

  <span class="keyword">if</span> (<span class="keyword">this</span>.paused) {
    <span class="keyword">this</span>._buffer || (<span class="keyword">this</span>._buffer = []);
    <span class="keyword">this</span>._buffer.push([err, doc]);
    <span class="keyword">return</span>;
  }

  <span class="keyword">if</span> (err) <span class="keyword">return</span> <span class="keyword">this</span>.destroy(err);

  <span class="comment">// when doc is null we hit the end of the cursor</span>
  <span class="keyword">if</span> (!doc) {
    <span class="keyword">this</span>.emit(<span class="string">'end'</span>);
    <span class="keyword">return</span> <span class="keyword">this</span>.destroy();
  }

  <span class="keyword">if</span> (<span class="keyword">this</span>.query.options &amp;&amp; <span class="keyword">this</span>.query.options.lean === <span class="literal">true</span>)  {
    <span class="keyword">this</span>.emit(<span class="string">'data'</span>, doc);

    <span class="comment">// trampoline management</span>
    <span class="keyword">if</span> (T_IDLE === <span class="keyword">this</span>._inline) {
      <span class="comment">// no longer in trampoline. restart it.</span>
      <span class="keyword">this</span>._next();
    } <span class="keyword">else</span> {
      <span class="comment">// in a trampoline. tell __next that its</span>
      <span class="comment">// ok to continue jumping.</span>
      <span class="keyword">this</span>._inline = T_CONT;
    }
    <span class="keyword">return</span>;
  }

  <span class="keyword">var</span> instance = <span class="keyword">new</span> <span class="keyword">this</span>.query.model(<span class="literal">undefined</span>, <span class="keyword">this</span>._fields, <span class="literal">true</span>);

  <span class="keyword">var</span> self = <span class="keyword">this</span>;
  instance.init(doc, <span class="keyword">this</span>.query, <span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
    <span class="keyword">if</span> (err) <span class="keyword">return</span> self.destroy(err);
    self.emit(<span class="string">'data'</span>, instance);

    <span class="comment">// trampoline management</span>
    <span class="keyword">if</span> (T_IDLE === self._inline) {
      <span class="comment">// no longer in trampoline. restart it.</span>
      self._next();
    } <span class="keyword">else</span>
      <span class="comment">// in a trampoline. tell __next that its</span>
      <span class="comment">// ok to continue jumping.</span>
      self._inline = T_CONT;
  });
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>err</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error">Error</a>, <a href="#null">null</a>&gt; </span><span></span></li><li><code>doc</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="querystream_QueryStream-pause"><a href="#querystream_QueryStream-pause">QueryStream#pause()</a></h3><p>Pauses this stream.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">QueryStream.prototype.pause = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">this</span>.paused = <span class="literal">true</span>;
}</code></pre></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="querystream_QueryStream-resume"><a href="#querystream_QueryStream-resume">QueryStream#resume()</a></h3><p>Resumes this stream.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">QueryStream.prototype.resume = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">this</span>.paused = <span class="literal">false</span>;
  <span class="keyword">this</span>._next();
}</code></pre></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="querystream_QueryStream-destroy"><a href="#querystream_QueryStream-destroy">QueryStream#destroy(<code>[err]</code>)</a></h3><p>Destroys the stream, closing the underlying cursor. No more events will be emitted.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">QueryStream.prototype.destroy = <span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
  <span class="keyword">if</span> (<span class="keyword">this</span>._destroyed) <span class="keyword">return</span>;
  <span class="keyword">this</span>._destroyed = <span class="literal">true</span>;
  <span class="keyword">this</span>.readable = <span class="literal">false</span>;

  <span class="keyword">if</span> (<span class="keyword">this</span>._cursor) {
    <span class="keyword">this</span>._cursor.close();
  }

  <span class="keyword">if</span> (err) {
    <span class="keyword">this</span>.emit(<span class="string">'error'</span>, err);
  }

  <span class="keyword">this</span>.emit(<span class="string">'close'</span>);
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>[err]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error">Error</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="querystream_QueryStream-pipe"><a href="#querystream_QueryStream-pipe">QueryStream#pipe()</a></h3><p>Pipes this query stream into another stream. This method is inherited from NodeJS Streams.</p><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://nodejs.org/api/stream.html" title="NodeJS">NodeJS</a></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code>query.stream().pipe(writeStream [, options])</code></pre>

<p>This could be particularily useful if you are, for example, setting up an API for a service and want to stream out the docs based on some criteria. We could first pipe the QueryStream into a sort of filter that formats the stream as an array before passing on the document to an http response.</p>

<pre><code><span class="keyword">var</span> format = <span class="keyword">new</span> ArrayFormatter;
Events.find().stream().pipe(format).pipe(res);</code></pre>

<p>As long as ArrayFormat implements the WriteStream API we can stream large formatted result sets out to the client. See this <a href="https://gist.github.com/1403797">gist</a> for a hacked example.</p></div><hr class=""></div><div class="item property public"><h3 id="querystream_QueryStream-paused"><a href="#querystream_QueryStream-paused">QueryStream#<span>paused</span></a></h3><p>Flag stating whether or not this stream is paused.</p><hr class=""></div><div class="item property public"><h3 id="querystream_QueryStream-readable"><a href="#querystream_QueryStream-readable">QueryStream#<span>readable</span></a></h3><p>Flag stating whether or not this stream is readable.</p><hr class=""></div></li><li class="module private"><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/schema/array.js" id="schema-array-js">schema/array.js</a><div class="item method private"><h3 id="schema_array_SchemaArray"><a href="#schema_array_SchemaArray">SchemaArray(<code>key</code>, <code>cast</code>, <code>options</code>)</a></h3><p>Array SchemaType constructor</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">SchemaArray</span> <span class="params">(key, cast, options)</span> {</span>
  <span class="keyword">if</span> (cast) {
    <span class="keyword">var</span> castOptions = {};

    <span class="keyword">if</span> (<span class="string">'Object'</span> === cast.constructor.name) {
      <span class="keyword">if</span> (cast.type) {
        <span class="comment">// support { type: Woot }</span>
        castOptions = cast;
        cast = cast.type;
        <span class="keyword">delete</span> castOptions.type;
      } <span class="keyword">else</span> {
        cast = Mixed;
      }
    }

    <span class="keyword">var</span> caster = cast.name <span class="keyword">in</span> Types ? Types[cast.name] : cast;
    <span class="keyword">this</span>.casterConstructor = caster;
    <span class="keyword">this</span>.caster = <span class="keyword">new</span> caster(<span class="literal">null</span>, castOptions);
  }

  SchemaType.call(<span class="keyword">this</span>, key, options);

  <span class="keyword">var</span> self = <span class="keyword">this</span>
    , defaultArr
    , fn;

  <span class="keyword">if</span> (<span class="keyword">this</span>.defaultValue) {
    defaultArr = <span class="keyword">this</span>.defaultValue;
    fn = <span class="string">'function'</span> == <span class="keyword">typeof</span> defaultArr;
  }

  <span class="keyword">this</span>.<span class="keyword">default</span>(<span class="keyword">function</span>(){
    <span class="keyword">var</span> arr = fn ? defaultArr() : defaultArr || [];
    <span class="keyword">return</span> <span class="keyword">new</span> MongooseArray(arr, self.path, <span class="keyword">this</span>);
  });
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>key</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>cast</code><span class="types"> &lt;<a href="#schematype_SchemaType">SchemaType</a>&gt; </span><span></span></li><li><code>options</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="#schematype_SchemaType">SchemaType</a></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_array_SchemaArray-checkRequired"><a href="#schema_array_SchemaArray-checkRequired">SchemaArray#checkRequired(<code>value</code>)</a></h3><p>Check required</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaArray.prototype.checkRequired = <span class="function"><span class="keyword">function</span> <span class="params">(value)</span> {</span>
  <span class="keyword">return</span> !!(value &amp;&amp; value.length);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>value</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array">Array</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_array_SchemaArray-applyGetters"><a href="#schema_array_SchemaArray-applyGetters">SchemaArray#applyGetters(<code>value</code>, <code>scope</code>)</a></h3><p>Overrides the getters application for the population special-case</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaArray.prototype.applyGetters = <span class="function"><span class="keyword">function</span> <span class="params">(value, scope)</span> {</span>
  <span class="keyword">if</span> (<span class="keyword">this</span>.caster.options &amp;&amp; <span class="keyword">this</span>.caster.options.ref) {
    <span class="comment">// means the object id was populated</span>
    <span class="keyword">return</span> value;
  }

  <span class="keyword">return</span> SchemaType.prototype.applyGetters.call(<span class="keyword">this</span>, value, scope);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>value</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>scope</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_array_SchemaArray-cast"><a href="#schema_array_SchemaArray-cast">SchemaArray#cast(<code>value</code>, <code>doc</code>, <code>init</code>)</a></h3><p>Casts contents</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaArray.prototype.cast = <span class="function"><span class="keyword">function</span> <span class="params">(value, doc, init)</span> {</span>
  <span class="keyword">if</span> (Array.isArray(value)) {
    <span class="keyword">if</span> (!(value <span class="keyword">instanceof</span> MongooseArray)) {
      value = <span class="keyword">new</span> MongooseArray(value, <span class="keyword">this</span>.path, doc);
    }

    <span class="keyword">if</span> (<span class="keyword">this</span>.caster) {
      <span class="keyword">try</span> {
        <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>, l = value.length; i &lt; l; i++) {
          value[i] = <span class="keyword">this</span>.caster.cast(value[i], doc, init);
        }
      } <span class="keyword">catch</span> (e) {
        <span class="comment">// rethrow</span>
        <span class="keyword">throw</span> <span class="keyword">new</span> CastError(e.type, value);
      }
    }

    <span class="keyword">return</span> value;
  } <span class="keyword">else</span> {
    <span class="keyword">return</span> <span class="keyword">this</span>.cast([value], doc, init);
  }
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>value</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>doc</code><span class="types"> &lt;<a href="#document_Document">Document</a>&gt; </span><span>document that triggers the casting</span></li><li><code>init</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span>whether this is an initialization cast</span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_array_SchemaArray-castForQuery"><a href="#schema_array_SchemaArray-castForQuery">SchemaArray#castForQuery(<code>$conditional</code>, <code>[value]</code>)</a></h3><p>Casts contents for queries.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaArray.prototype.castForQuery = <span class="function"><span class="keyword">function</span> <span class="params">($conditional, value)</span> {</span>
  <span class="keyword">var</span> handler
    , val;
  <span class="keyword">if</span> (arguments.length === <span class="number">2</span>) {
    handler = <span class="keyword">this</span>.$conditionalHandlers[$conditional];
    <span class="keyword">if</span> (!handler)
      <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">"Can't use "</span> + $conditional + <span class="string">" with Array."</span>);
    val = handler.call(<span class="keyword">this</span>, value);
  } <span class="keyword">else</span> {
    val = $conditional;
    <span class="keyword">var</span> proto = <span class="keyword">this</span>.casterConstructor.prototype;
    <span class="keyword">var</span> method = proto.castForQuery || proto.cast;
    <span class="keyword">if</span> (Array.isArray(val)) {
      val = val.map(<span class="function"><span class="keyword">function</span> <span class="params">(v)</span> {</span>
        <span class="keyword">if</span> (method) v = method.call(proto, v);
        <span class="keyword">return</span> isMongooseObject(v)
          ? v.toObject()
          : v;
      });
    } <span class="keyword">else</span> <span class="keyword">if</span> (method) {
      val = method.call(proto, val);
    }
  }
  <span class="keyword">return</span> val &amp;&amp; isMongooseObject(val)
    ? val.toObject()
    : val;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>$conditional</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>[value]</code><span class="types"> &lt;<a href="#any">any</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div></li><li class="module private"><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/schema/boolean.js" id="schema-boolean-js">schema/boolean.js</a><div class="item method private"><h3 id="schema_boolean_SchemaBoolean"><a href="#schema_boolean_SchemaBoolean">SchemaBoolean(<code>path</code>, <code>options</code>)</a></h3><p>Boolean SchemaType constructor.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">SchemaBoolean</span> <span class="params">(path, options)</span> {</span>
  SchemaType.call(<span class="keyword">this</span>, path, options);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>options</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="#schematype_SchemaType">SchemaType</a></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_boolean_SchemaBoolean-checkRequired"><a href="#schema_boolean_SchemaBoolean-checkRequired">SchemaBoolean#checkRequired()</a></h3><p>Required validator</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaBoolean.prototype.checkRequired = <span class="function"><span class="keyword">function</span> <span class="params">(value)</span> {</span>
  <span class="keyword">return</span> value === <span class="literal">true</span> || value === <span class="literal">false</span>;
};</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_boolean_SchemaBoolean-cast"><a href="#schema_boolean_SchemaBoolean-cast">SchemaBoolean#cast(<code>value</code>)</a></h3><p>Casts to boolean</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaBoolean.prototype.cast = <span class="function"><span class="keyword">function</span> <span class="params">(value)</span> {</span>
  <span class="keyword">if</span> (value === <span class="literal">null</span>) <span class="keyword">return</span> value;
  <span class="keyword">if</span> (value === <span class="string">'0'</span>) <span class="keyword">return</span> <span class="literal">false</span>;
  <span class="keyword">return</span> !!value;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>value</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_boolean_SchemaBoolean-castForQuery"><a href="#schema_boolean_SchemaBoolean-castForQuery">SchemaBoolean#castForQuery(<code>$conditional</code>, <code>val</code>)</a></h3><p>Casts contents for queries.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaBoolean.prototype.castForQuery = <span class="function"><span class="keyword">function</span> <span class="params">($conditional, val)</span> {</span>
  <span class="keyword">var</span> handler;
  <span class="keyword">if</span> (<span class="number">2</span> === arguments.length) {
    handler = SchemaBoolean.$conditionalHandlers[$conditional];

    <span class="keyword">if</span> (handler) {
      <span class="keyword">return</span> handler.call(<span class="keyword">this</span>, val);
    }

    <span class="keyword">return</span> <span class="keyword">this</span>.cast(val);
  }

  <span class="keyword">return</span> <span class="keyword">this</span>.cast($conditional);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>$conditional</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>val</code><span class="types"> &lt;<a href="#any">any</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div></li><li class="module private"><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/schema/buffer.js" id="schema-buffer-js">schema/buffer.js</a><div class="item method private"><h3 id="schema_buffer_SchemaBuffer"><a href="#schema_buffer_SchemaBuffer">SchemaBuffer(<code>key</code>, <code>cast</code>)</a></h3><p>Buffer SchemaType constructor</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">SchemaBuffer</span> <span class="params">(key, options)</span> {</span>
  SchemaType.call(<span class="keyword">this</span>, key, options, <span class="string">'Buffer'</span>);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>key</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>cast</code><span class="types"> &lt;<a href="#schematype_SchemaType">SchemaType</a>&gt; </span><span></span></li></ul></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="#schematype_SchemaType">SchemaType</a></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_buffer_SchemaBuffer-checkRequired"><a href="#schema_buffer_SchemaBuffer-checkRequired">SchemaBuffer#checkRequired()</a></h3><p>Check required</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaBuffer.prototype.checkRequired = <span class="function"><span class="keyword">function</span> <span class="params">(value)</span> {</span>
  <span class="keyword">return</span> !!(value &amp;&amp; value.length);
};</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_buffer_SchemaBuffer-cast"><a href="#schema_buffer_SchemaBuffer-cast">SchemaBuffer#cast(<code>value</code>, <code>doc</code>, <code>init</code>)</a></h3><p>Casts contents</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaBuffer.prototype.cast = <span class="function"><span class="keyword">function</span> <span class="params">(value, doc, init)</span> {</span>
  <span class="keyword">if</span> (SchemaType._isRef(<span class="keyword">this</span>, value, init)) <span class="keyword">return</span> value;

  <span class="keyword">if</span> (Buffer.isBuffer(value)) {
    <span class="keyword">if</span> (!(value <span class="keyword">instanceof</span> MongooseBuffer)) {
      value = <span class="keyword">new</span> MongooseBuffer(value, [<span class="keyword">this</span>.path, doc]);
    }

    <span class="keyword">return</span> value;
  } <span class="keyword">else</span> <span class="keyword">if</span> (value <span class="keyword">instanceof</span> Binary) {
    <span class="keyword">return</span> <span class="keyword">new</span> MongooseBuffer(value.value(<span class="literal">true</span>), [<span class="keyword">this</span>.path, doc]);
  }

  <span class="keyword">if</span> (<span class="string">'string'</span> === <span class="keyword">typeof</span> value || Array.isArray(value)) {
    <span class="keyword">return</span> <span class="keyword">new</span> MongooseBuffer(value, [<span class="keyword">this</span>.path, doc]);
  }

  <span class="keyword">throw</span> <span class="keyword">new</span> CastError(<span class="string">'buffer'</span>, value);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>value</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>doc</code><span class="types"> &lt;<a href="#document_Document">Document</a>&gt; </span><span>document that triggers the casting</span></li><li><code>init</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_buffer_SchemaBuffer-castForQuery"><a href="#schema_buffer_SchemaBuffer-castForQuery">SchemaBuffer#castForQuery(<code>$conditional</code>, <code>[value]</code>)</a></h3><p>Casts contents for queries.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaBuffer.prototype.castForQuery = <span class="function"><span class="keyword">function</span> <span class="params">($conditional, val)</span> {</span>
  <span class="keyword">var</span> handler;
  <span class="keyword">if</span> (arguments.length === <span class="number">2</span>) {
    handler = <span class="keyword">this</span>.$conditionalHandlers[$conditional];
    <span class="keyword">if</span> (!handler)
      <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">"Can't use "</span> + $conditional + <span class="string">" with Buffer."</span>);
    <span class="keyword">return</span> handler.call(<span class="keyword">this</span>, val);
  } <span class="keyword">else</span> {
    val = $conditional;
    <span class="keyword">return</span> <span class="keyword">this</span>.cast(val).toObject();
  }
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>$conditional</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>[value]</code><span class="types"> &lt;<a href="#any">any</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div></li><li class="module private"><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/schema/date.js" id="schema-date-js">schema/date.js</a><div class="item method private"><h3 id="schema_date_SchemaDate"><a href="#schema_date_SchemaDate">SchemaDate(<code>key</code>, <code>options</code>)</a></h3><p>Date SchemaType constructor.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">SchemaDate</span> <span class="params">(key, options)</span> {</span>
  SchemaType.call(<span class="keyword">this</span>, key, options);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>key</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>options</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="#schematype_SchemaType">SchemaType</a></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_date_SchemaDate-checkRequired"><a href="#schema_date_SchemaDate-checkRequired">SchemaDate#checkRequired()</a></h3><p>Required validator for date</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaDate.prototype.checkRequired = <span class="function"><span class="keyword">function</span> <span class="params">(value)</span> {</span>
  <span class="keyword">return</span> value <span class="keyword">instanceof</span> Date;
};</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_date_SchemaDate-cast"><a href="#schema_date_SchemaDate-cast">SchemaDate#cast(<code>value</code>)</a></h3><p>Casts to date</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaDate.prototype.cast = <span class="function"><span class="keyword">function</span> <span class="params">(value)</span> {</span>
  <span class="keyword">if</span> (value === <span class="literal">null</span> || value === <span class="string">''</span>)
    <span class="keyword">return</span> <span class="literal">null</span>;

  <span class="keyword">if</span> (value <span class="keyword">instanceof</span> Date)
    <span class="keyword">return</span> value;

  <span class="keyword">var</span> date;

  <span class="comment">// support for timestamps</span>
  <span class="keyword">if</span> (value <span class="keyword">instanceof</span> Number || <span class="string">'number'</span> == <span class="keyword">typeof</span> value 
      || String(value) == Number(value))
    date = <span class="keyword">new</span> Date(Number(value));

  <span class="comment">// support for date strings</span>
  <span class="keyword">else</span> <span class="keyword">if</span> (value.toString)
    date = <span class="keyword">new</span> Date(value.toString());

  <span class="keyword">if</span> (date.toString() != <span class="string">'Invalid Date'</span>)
    <span class="keyword">return</span> date;

  <span class="keyword">throw</span> <span class="keyword">new</span> CastError(<span class="string">'date'</span>, value);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>value</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>to cast</span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_date_SchemaDate-castForQuery"><a href="#schema_date_SchemaDate-castForQuery">SchemaDate#castForQuery(<code>$conditional</code>, <code>[value]</code>)</a></h3><p>Casts contents for queries.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaDate.prototype.castForQuery = <span class="function"><span class="keyword">function</span> <span class="params">($conditional, val)</span> {</span>
  <span class="keyword">var</span> handler;

  <span class="keyword">if</span> (<span class="number">2</span> !== arguments.length) {
    <span class="keyword">return</span> <span class="keyword">this</span>.cast($conditional);
  }

  handler = <span class="keyword">this</span>.$conditionalHandlers[$conditional];

  <span class="keyword">if</span> (!handler) {
    <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">"Can't use "</span> + $conditional + <span class="string">" with Date."</span>);
  }

  <span class="keyword">return</span> handler.call(<span class="keyword">this</span>, val);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>$conditional</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>[value]</code><span class="types"> &lt;<a href="#any">any</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div></li><li class="module private"><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/schema/documentarray.js" id="schema-documentarray-js">schema/documentarray.js</a><div class="item method private"><h3 id="schema_documentarray_DocumentArray"><a href="#schema_documentarray_DocumentArray">DocumentArray(<code>key</code>, <code>schema</code>, <code>options</code>)</a></h3><p>SubdocsArray SchemaType constructor</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">DocumentArray</span> <span class="params">(key, schema, options)</span> {</span>

  <span class="comment">// compile an embedded document for this schema</span>
  <span class="function"><span class="keyword">function</span> <span class="title">EmbeddedDocument</span> <span class="params">()</span> {</span>
    Subdocument.apply(<span class="keyword">this</span>, arguments);
  }

  EmbeddedDocument.prototype.__proto__ = Subdocument.prototype;
  EmbeddedDocument.prototype._setSchema(schema);
  EmbeddedDocument.schema = schema;

  <span class="comment">// apply methods</span>
  <span class="keyword">for</span> (<span class="keyword">var</span> i <span class="keyword">in</span> schema.methods) {
    EmbeddedDocument.prototype[i] = schema.methods[i];
  }

  <span class="comment">// apply statics</span>
  <span class="keyword">for</span> (<span class="keyword">var</span> i <span class="keyword">in</span> schema.statics)
    EmbeddedDocument[i] = schema.statics[i];

  EmbeddedDocument.options = options;
  <span class="keyword">this</span>.schema = schema;

  ArrayType.call(<span class="keyword">this</span>, key, EmbeddedDocument, options);

  <span class="keyword">this</span>.schema = schema;
  <span class="keyword">var</span> path = <span class="keyword">this</span>.path;
  <span class="keyword">var</span> fn = <span class="keyword">this</span>.defaultValue;

  <span class="keyword">this</span>.<span class="keyword">default</span>(<span class="keyword">function</span>(){
    <span class="keyword">var</span> arr = fn.call(<span class="keyword">this</span>);
    <span class="keyword">if</span> (!Array.isArray(arr)) arr = [arr];
    <span class="keyword">return</span> <span class="keyword">new</span> MongooseDocumentArray(arr, path, <span class="keyword">this</span>);
  });
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>key</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>schema</code><span class="types"> &lt;<a href="#schema_Schema">Schema</a>&gt; </span><span></span></li><li><code>options</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="#schema_array_SchemaArray">SchemaArray</a></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_documentarray_DocumentArray-doValidate"><a href="#schema_documentarray_DocumentArray-doValidate">DocumentArray#doValidate()</a></h3><p>Performs local validations first, then validations on each embedded doc</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">DocumentArray.prototype.doValidate = <span class="function"><span class="keyword">function</span> <span class="params">(array, fn, scope)</span> {</span>
  <span class="keyword">var</span> self = <span class="keyword">this</span>;
  SchemaType.prototype.doValidate.call(<span class="keyword">this</span>, array, <span class="keyword">function</span>(err){
    <span class="keyword">if</span> (err) <span class="keyword">return</span> fn(err);

    <span class="keyword">var</span> count = array &amp;&amp; array.length
      , error = <span class="literal">false</span>;

    <span class="keyword">if</span> (!count) <span class="keyword">return</span> fn();

    array.forEach(<span class="keyword">function</span>(doc, index){
      doc.validate(<span class="keyword">function</span>(err){
        <span class="keyword">if</span> (err &amp;&amp; !error){
          <span class="comment">// rewrite they key</span>
          err.key = self.key + <span class="string">'.'</span> + index + <span class="string">'.'</span> + err.key;
          fn(err);
          error = <span class="literal">true</span>;
        } <span class="keyword">else</span> {
          --count || fn();
        }
      });
    });
  }, scope);
};</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_documentarray_DocumentArray-cast"><a href="#schema_documentarray_DocumentArray-cast">DocumentArray#cast(<code>value</code>, <code>document</code>)</a></h3><p>Casts contents</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">DocumentArray.prototype.cast = <span class="function"><span class="keyword">function</span> <span class="params">(value, doc, init, prev)</span> {</span>
  <span class="keyword">var</span> selected
    , subdoc
    , i

  <span class="keyword">if</span> (!Array.isArray(value)) {
    <span class="keyword">return</span> <span class="keyword">this</span>.cast([value], doc, init, prev);
  }

  <span class="keyword">if</span> (!(value <span class="keyword">instanceof</span> MongooseDocumentArray)) {
    value = <span class="keyword">new</span> MongooseDocumentArray(value, <span class="keyword">this</span>.path, doc);
  }

  i = value.length;

  <span class="keyword">while</span> (i--) {
    <span class="keyword">if</span> (!(value[i] <span class="keyword">instanceof</span> Subdocument)) {
      <span class="keyword">if</span> (init) {
        selected || (selected = scopePaths(<span class="keyword">this</span>, doc._selected, init));
        subdoc = <span class="keyword">new</span> <span class="keyword">this</span>.casterConstructor(<span class="literal">null</span>, value, <span class="literal">true</span>, selected);
        value[i] = subdoc.init(value[i]);
      } <span class="keyword">else</span> {
        <span class="keyword">if</span> (prev &amp;&amp; (subdoc = prev.id(value[i]._id))) {
          <span class="comment">// handle resetting doc with existing id but differing data</span>
          <span class="comment">// doc.array = [{ doc: 'val' }]</span>
          subdoc.set(value[i]);
        } <span class="keyword">else</span> {
          subdoc = <span class="keyword">new</span> <span class="keyword">this</span>.casterConstructor(value[i], value);
        }

        <span class="comment">// if set() is hooked it will have no return value</span>
        <span class="comment">// see gh-746</span>
        value[i] = subdoc;
      }
    }
  }

  <span class="keyword">return</span> value;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>value</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>document</code><span class="types"> &lt;<a href="#document_Document">Document</a>&gt; </span><span>that triggers the casting</span></li></ul></div><div class="description"></div><hr class="private"></div></li><li class="module private"><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/schema/mixed.js" id="schema-mixed-js">schema/mixed.js</a><div class="item method private"><h3 id="schema_mixed_Mixed"><a href="#schema_mixed_Mixed">Mixed(<code>path</code>, <code>options</code>)</a></h3><p>Mixed SchemaType constructor.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">Mixed</span> <span class="params">(path, options)</span> {</span>
  <span class="comment">// make sure empty array defaults are handled</span>
  <span class="keyword">if</span> (options &amp;&amp;
      options.<span class="keyword">default</span> &amp;&amp;
      Array.isArray(options.<span class="keyword">default</span>) &amp;&amp;
      <span class="number">0</span> === options.<span class="keyword">default</span>.length) {
    options.<span class="keyword">default</span> = Array;
  }

  SchemaType.call(<span class="keyword">this</span>, path, options);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>options</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="#schematype_SchemaType">SchemaType</a></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_mixed_Mixed-checkRequired"><a href="#schema_mixed_Mixed-checkRequired">Mixed#checkRequired()</a></h3><p>Required validator</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Mixed.prototype.checkRequired = <span class="function"><span class="keyword">function</span> <span class="params">(val)</span> {</span>
  <span class="keyword">return</span> <span class="literal">true</span>;
};</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_mixed_Mixed-cast"><a href="#schema_mixed_Mixed-cast">Mixed#cast(<code>value</code>)</a></h3><p>Casts <code>val</code> for Mixed.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Mixed.prototype.cast = <span class="function"><span class="keyword">function</span> <span class="params">(val)</span> {</span>
  <span class="keyword">return</span> val;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>value</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>to cast</span></li></ul></div><div class="description"><p><em>this is a no-op</em></p></div><hr class="private"></div><div class="item method private"><h3 id="schema_mixed_Mixed-castForQuery"><a href="#schema_mixed_Mixed-castForQuery">Mixed#castForQuery(<code>$cond</code>, <code>[val]</code>)</a></h3><p>Casts contents for queries.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Mixed.prototype.castForQuery = <span class="function"><span class="keyword">function</span> <span class="params">($cond, val)</span> {</span>
  <span class="keyword">if</span> (arguments.length === <span class="number">2</span>) <span class="keyword">return</span> val;
  <span class="keyword">return</span> $cond;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>$cond</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>[val]</code><span class="types"> &lt;<a href="#any">any</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div></li><li class="module "><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/schema/number.js" id="schema-number-js">schema/number.js</a><div class="item method private"><h3 id="schema_number_SchemaNumber"><a href="#schema_number_SchemaNumber">SchemaNumber(<code>key</code>, <code>options</code>)</a></h3><p>Number SchemaType constructor.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">SchemaNumber</span> <span class="params">(key, options)</span> {</span>
  SchemaType.call(<span class="keyword">this</span>, key, options, <span class="string">'Number'</span>);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>key</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>options</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="#schematype_SchemaType">SchemaType</a></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_number_SchemaNumber-checkRequired"><a href="#schema_number_SchemaNumber-checkRequired">SchemaNumber#checkRequired()</a></h3><p>Required validator for number</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaNumber.prototype.checkRequired = <span class="function"><span class="keyword">function</span> <span class="title">checkRequired</span> <span class="params">(value)</span> {</span>
  <span class="keyword">if</span> (SchemaType._isRef(<span class="keyword">this</span>, value, <span class="literal">true</span>)) {
    <span class="keyword">return</span> <span class="literal">null</span> != value;
  } <span class="keyword">else</span> {
    <span class="keyword">return</span> <span class="keyword">typeof</span> value == <span class="string">'number'</span> || value <span class="keyword">instanceof</span> Number;
  }
};</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="schema_number_SchemaNumber-min"><a href="#schema_number_SchemaNumber-min">SchemaNumber#min(<code>value</code>, <code>message</code>)</a></h3><p>Sets a maximum number validator.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaNumber.prototype.min = <span class="function"><span class="keyword">function</span> <span class="params">(value, message)</span> {</span>
  <span class="keyword">if</span> (<span class="keyword">this</span>.minValidator)
    <span class="keyword">this</span>.validators = <span class="keyword">this</span>.validators.filter(<span class="keyword">function</span>(v){
      <span class="keyword">return</span> v[<span class="number">1</span>] != <span class="string">'min'</span>;
    });
  <span class="keyword">if</span> (value != <span class="literal">null</span>)
    <span class="keyword">this</span>.validators.push([<span class="keyword">function</span>(v){
      <span class="keyword">return</span> v === <span class="literal">null</span> || v >= value;
    }, <span class="string">'min'</span>]);
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>value</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span>minimum number</span></li><li><code>message</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code><span class="keyword">var</span> s = <span class="keyword">new</span> Schema({ n: { type: Number, min: <span class="number">10</span> })
<span class="keyword">var</span> M = db.model(<span class="string">'M'</span>, s)
<span class="keyword">var</span> m = <span class="keyword">new</span> M({ n: <span class="number">9</span> })
m.save(<span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
  console.error(err) <span class="comment">// validator error</span>
  m.n = <span class="number">10</span>;
  m.save() <span class="comment">// success</span>
})</code></pre></div><hr class=""></div><div class="item method public"><h3 id="schema_number_SchemaNumber-max"><a href="#schema_number_SchemaNumber-max">SchemaNumber#max(<code>maximum</code>, <code>message</code>)</a></h3><p>Sets a maximum number validator.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaNumber.prototype.max = <span class="function"><span class="keyword">function</span> <span class="params">(value, message)</span> {</span>
  <span class="keyword">if</span> (<span class="keyword">this</span>.maxValidator)
    <span class="keyword">this</span>.validators = <span class="keyword">this</span>.validators.filter(<span class="keyword">function</span>(v){
      <span class="keyword">return</span> v[<span class="number">1</span>] != <span class="string">'max'</span>;
    });
  <span class="keyword">if</span> (value != <span class="literal">null</span>)
    <span class="keyword">this</span>.validators.push([<span class="keyword">this</span>.maxValidator = <span class="keyword">function</span>(v){
      <span class="keyword">return</span> v === <span class="literal">null</span> || v &lt;= value;
    }, <span class="string">'max'</span>]);
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>maximum</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span>number</span></li><li><code>message</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code><span class="keyword">var</span> s = <span class="keyword">new</span> Schema({ n: { type: Number, max: <span class="number">10</span> })
<span class="keyword">var</span> M = db.model(<span class="string">'M'</span>, s)
<span class="keyword">var</span> m = <span class="keyword">new</span> M({ n: <span class="number">11</span> })
m.save(<span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
  console.error(err) <span class="comment">// validator error</span>
  m.n = <span class="number">10</span>;
  m.save() <span class="comment">// success</span>
})</code></pre></div><hr class=""></div><div class="item method private"><h3 id="schema_number_SchemaNumber-cast"><a href="#schema_number_SchemaNumber-cast">SchemaNumber#cast(<code>value</code>, <code>doc</code>, <code>init</code>)</a></h3><p>Casts to number</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaNumber.prototype.cast = <span class="function"><span class="keyword">function</span> <span class="params">(value, doc, init)</span> {</span>
  <span class="keyword">if</span> (SchemaType._isRef(<span class="keyword">this</span>, value, init)) <span class="keyword">return</span> value;

  <span class="keyword">if</span> (!isNaN(value)){
    <span class="keyword">if</span> (<span class="literal">null</span> === value) <span class="keyword">return</span> value;
    <span class="keyword">if</span> (<span class="string">''</span> === value) <span class="keyword">return</span> <span class="literal">null</span>;
    <span class="keyword">if</span> (<span class="string">'string'</span> == <span class="keyword">typeof</span> value) value = Number(value);
    <span class="keyword">if</span> (value <span class="keyword">instanceof</span> Number) <span class="keyword">return</span> value
    <span class="keyword">if</span> (<span class="string">'number'</span> == <span class="keyword">typeof</span> value) <span class="keyword">return</span> value;
    <span class="keyword">if</span> (value.toString &amp;&amp; !Array.isArray(value) &amp;&amp;
        value.toString() == Number(value)) {
      <span class="keyword">return</span> <span class="keyword">new</span> Number(value)
    }
  }

  <span class="keyword">throw</span> <span class="keyword">new</span> CastError(<span class="string">'number'</span>, value);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>value</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>value to cast</span></li><li><code>doc</code><span class="types"> &lt;<a href="#document_Document">Document</a>&gt; </span><span>document that triggers the casting</span></li><li><code>init</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_number_SchemaNumber-castForQuery"><a href="#schema_number_SchemaNumber-castForQuery">SchemaNumber#castForQuery(<code>$conditional</code>, <code>[value]</code>)</a></h3><p>Casts contents for queries.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaNumber.prototype.castForQuery = <span class="function"><span class="keyword">function</span> <span class="params">($conditional, val)</span> {</span>
  <span class="keyword">var</span> handler;
  <span class="keyword">if</span> (arguments.length === <span class="number">2</span>) {
    handler = <span class="keyword">this</span>.$conditionalHandlers[$conditional];
    <span class="keyword">if</span> (!handler)
      <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">"Can't use "</span> + $conditional + <span class="string">" with Number."</span>);
    <span class="keyword">return</span> handler.call(<span class="keyword">this</span>, val);
  } <span class="keyword">else</span> {
    val = <span class="keyword">this</span>.cast($conditional);
    <span class="keyword">return</span> val == <span class="literal">null</span> ? val : val
  }
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>$conditional</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>[value]</code><span class="types"> &lt;<a href="#any">any</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div></li><li class="module private"><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/schema/objectid.js" id="schema-objectid-js">schema/objectid.js</a><div class="item method private"><h3 id="schema_objectid_ObjectId"><a href="#schema_objectid_ObjectId">ObjectId(<code>key</code>, <code>options</code>)</a></h3><p>ObjectId SchemaType constructor.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">ObjectId</span> <span class="params">(key, options)</span> {</span>
  SchemaType.call(<span class="keyword">this</span>, key, options, <span class="string">'ObjectID'</span>);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>key</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>options</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="#schematype_SchemaType">SchemaType</a></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_objectid_ObjectId-checkRequired"><a href="#schema_objectid_ObjectId-checkRequired">ObjectId#checkRequired()</a></h3><p>Check required</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">ObjectId.prototype.checkRequired = <span class="function"><span class="keyword">function</span> <span class="title">checkRequired</span> <span class="params">(value)</span> {</span>
  <span class="keyword">if</span> (SchemaType._isRef(<span class="keyword">this</span>, value, <span class="literal">true</span>)) {
    <span class="keyword">return</span> <span class="literal">null</span> != value;
  } <span class="keyword">else</span> {
    <span class="keyword">return</span> value <span class="keyword">instanceof</span> oid;
  }
};</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_objectid_ObjectId-cast"><a href="#schema_objectid_ObjectId-cast">ObjectId#cast(<code>value</code>, <code>scope</code>, <code>init</code>)</a></h3><p>Casts to ObjectId</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">ObjectId.prototype.cast = <span class="function"><span class="keyword">function</span> <span class="params">(value, scope, init)</span> {</span>
  <span class="keyword">if</span> (SchemaType._isRef(<span class="keyword">this</span>, value, init)) <span class="keyword">return</span> value;

  <span class="keyword">if</span> (value === <span class="literal">null</span>) <span class="keyword">return</span> value;

  <span class="keyword">if</span> (value <span class="keyword">instanceof</span> oid)
    <span class="keyword">return</span> value;

  <span class="keyword">if</span> (value._id &amp;&amp; value._id <span class="keyword">instanceof</span> oid)
    <span class="keyword">return</span> value._id;

  <span class="keyword">if</span> (value.toString)
    <span class="keyword">return</span> oid.fromString(value.toString());

  <span class="keyword">throw</span> <span class="keyword">new</span> CastError(<span class="string">'object id'</span>, value);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>value</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>scope</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>init</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span>whether this is an initialization cast</span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_objectid_ObjectId-castForQuery"><a href="#schema_objectid_ObjectId-castForQuery">ObjectId#castForQuery(<code>$conditional</code>, <code>[val]</code>)</a></h3><p>Casts contents for queries.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">ObjectId.prototype.castForQuery = <span class="function"><span class="keyword">function</span> <span class="params">($conditional, val)</span> {</span>
  <span class="keyword">var</span> handler;
  <span class="keyword">if</span> (arguments.length === <span class="number">2</span>) {
    handler = <span class="keyword">this</span>.$conditionalHandlers[$conditional];
    <span class="keyword">if</span> (!handler)
      <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">"Can't use "</span> + $conditional + <span class="string">" with ObjectId."</span>);
    <span class="keyword">return</span> handler.call(<span class="keyword">this</span>, val);
  } <span class="keyword">else</span> {
    <span class="keyword">return</span> <span class="keyword">this</span>.cast($conditional);
  }
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>$conditional</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>[val]</code><span class="types"> &lt;<a href="#any">any</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_objectid_ObjectId-auto"><a href="#schema_objectid_ObjectId-auto">ObjectId#auto(<code>turnOn</code>)</a></h3><p>Adds an auto-generated ObjectId default if turnOn is true.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">ObjectId.prototype.auto = <span class="function"><span class="keyword">function</span> <span class="params">(turnOn)</span> {</span>
  <span class="keyword">if</span> (turnOn) {
    <span class="keyword">this</span>.<span class="keyword">default</span>(defaultId);
    <span class="keyword">this</span>.set(resetId)
  }
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>turnOn</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span>auto generated ObjectId defaults</span></li></ul></div><div class="description"></div><hr class="private"></div></li><li class="module "><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/schema/string.js" id="schema-string-js">schema/string.js</a><div class="item method private"><h3 id="schema_string_SchemaString"><a href="#schema_string_SchemaString">SchemaString(<code>key</code>, <code>options</code>)</a></h3><p>String SchemaType constructor.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">SchemaString</span> <span class="params">(key, options)</span> {</span>
  <span class="keyword">this</span>.enumValues = [];
  <span class="keyword">this</span>.regExp = <span class="literal">null</span>;
  SchemaType.call(<span class="keyword">this</span>, key, options, <span class="string">'String'</span>);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>key</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>options</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="#schematype_SchemaType">SchemaType</a></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="schema_string_SchemaString-enum"><a href="#schema_string_SchemaString-enum">SchemaString#enum(<code>[args...]</code>)</a></h3><p>Adds enumeration values and a coinciding validator.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaString.prototype.enum = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">var</span> len = arguments.length;
  <span class="keyword">if</span> (!len || <span class="literal">undefined</span> === arguments[<span class="number">0</span>] || <span class="literal">false</span> === arguments[<span class="number">0</span>]) {
    <span class="keyword">if</span> (<span class="keyword">this</span>.enumValidator){
      <span class="keyword">this</span>.enumValidator = <span class="literal">false</span>;
      <span class="keyword">this</span>.validators = <span class="keyword">this</span>.validators.filter(<span class="keyword">function</span>(v){
        <span class="keyword">return</span> v[<span class="number">1</span>] != <span class="string">'enum'</span>;
      });
    }
    <span class="keyword">return</span>;
  }

  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; len; i++) {
    <span class="keyword">if</span> (<span class="literal">undefined</span> !== arguments[i]) {
      <span class="keyword">this</span>.enumValues.push(<span class="keyword">this</span>.cast(arguments[i]));
    }
  }

  <span class="keyword">if</span> (!<span class="keyword">this</span>.enumValidator) {
    <span class="keyword">var</span> values = <span class="keyword">this</span>.enumValues;
    <span class="keyword">this</span>.enumValidator = <span class="keyword">function</span>(v){
      <span class="keyword">return</span> <span class="literal">undefined</span> === v || ~values.indexOf(v);
    };
    <span class="keyword">this</span>.validators.push([<span class="keyword">this</span>.enumValidator, <span class="string">'enum'</span>]);
  }
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>[args...]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>enumeration values</span></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code><span class="keyword">var</span> states = <span class="string">'opening open closing closed'</span>.split(<span class="string">' '</span>)
<span class="keyword">var</span> s = <span class="keyword">new</span> Schema({ state: { type: String, enum: states })
<span class="keyword">var</span> M = db.model(<span class="string">'M'</span>, s)
<span class="keyword">var</span> m = <span class="keyword">new</span> M({ state: <span class="string">'invalid'</span> })
m.save(<span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
  console.error(err) <span class="comment">// validator error</span>
  m.state = <span class="string">'open'</span>
  m.save() <span class="comment">// success</span>
})</code></pre></div><hr class=""></div><div class="item method public"><h3 id="schema_string_SchemaString-lowercase"><a href="#schema_string_SchemaString-lowercase">SchemaString#lowercase()</a></h3><p>Adds a lowercase setter.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaString.prototype.lowercase = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">return</span> <span class="keyword">this</span>.set(<span class="function"><span class="keyword">function</span> <span class="params">(v)</span> {</span>
    <span class="keyword">return</span> v.toLowerCase();
  });
};</code></pre></div><div class="description"><h4>Example:</h4>

<pre><code>var s = new Schema({ email: { type: String, lowercase: true }})
var M = db.model('M', s);
var m = new M({ email: '<a href='mailto:SomeEmail@example.COM'>SomeEmail@example.COM</a>' });
console.log(m.email) // <a href='mailto:someemail@example.com'>someemail@example.com</a>
</code></pre></div><hr class=""></div><div class="item method public"><h3 id="schema_string_SchemaString-uppercase"><a href="#schema_string_SchemaString-uppercase">SchemaString#uppercase()</a></h3><p>Adds an uppercase setter.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaString.prototype.uppercase = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">return</span> <span class="keyword">this</span>.set(<span class="function"><span class="keyword">function</span> <span class="params">(v)</span> {</span>
    <span class="keyword">return</span> v.toUpperCase();
  });
};</code></pre></div><div class="description"><h4>Example:</h4>

<pre><code><span class="keyword">var</span> s = <span class="keyword">new</span> Schema({ caps: { type: String, uppercase: <span class="literal">true</span> }})
<span class="keyword">var</span> M = db.model(<span class="string">'M'</span>, s);
<span class="keyword">var</span> m = <span class="keyword">new</span> M({ caps: <span class="string">'an example'</span> });
console.log(m.caps) <span class="comment">// AN EXAMPLE</span></code></pre></div><hr class=""></div><div class="item method public"><h3 id="schema_string_SchemaString-trim"><a href="#schema_string_SchemaString-trim">SchemaString#trim()</a></h3><p>Adds a trim setter.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaString.prototype.trim = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">return</span> <span class="keyword">this</span>.set(<span class="function"><span class="keyword">function</span> <span class="params">(v)</span> {</span>
    <span class="keyword">return</span> v.trim();
  });
};</code></pre></div><div class="description"><p>The string value will be trimmed when set.</p>

<h4>Example:</h4>

<pre><code><span class="keyword">var</span> s = <span class="keyword">new</span> Schema({ name: { type: String, trim: <span class="literal">true</span> }})
<span class="keyword">var</span> M = db.model(<span class="string">'M'</span>, s)
<span class="keyword">var</span> string = <span class="string">' some name '</span>
console.log(string.length) <span class="comment">// 11</span>
<span class="keyword">var</span> m = <span class="keyword">new</span> M({ name: string })
console.log(m.name.length) <span class="comment">// 9</span></code></pre></div><hr class=""></div><div class="item method public"><h3 id="schema_string_SchemaString-match"><a href="#schema_string_SchemaString-match">SchemaString#match(<code>regExp</code>)</a></h3><p>Sets a regexp validator.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaString.prototype.match = <span class="function"><span class="keyword">function</span> <span class="title">match</span> <span class="params">(regExp)</span> {</span>
  <span class="keyword">this</span>.validators.push([<span class="keyword">function</span>(v){
    <span class="keyword">return</span> <span class="literal">null</span> != v &amp;&amp; <span class="string">''</span> !== v
      ? regExp.test(v)
      : <span class="literal">true</span>
  }, <span class="string">'regexp'</span>]);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>regExp</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp">RegExp</a>&gt; </span><span>regular expression to test against</span></li></ul></div><div class="description"><p>Any value that does not pass <code>regExp</code>.test(val) will fail validation.</p>

<h4>Example:</h4>

<pre><code><span class="keyword">var</span> s = <span class="keyword">new</span> Schema({ name: { type: String, match: <span class="regexp">/^a/</span> }})
<span class="keyword">var</span> M = db.model(<span class="string">'M'</span>, s)
<span class="keyword">var</span> m = <span class="keyword">new</span> M({ name: <span class="string">'invalid'</span> })
m.validate(<span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
  console.error(err) <span class="comment">// validation error</span>
  m.name = <span class="string">'apples'</span>
  m.validate(<span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
    assert.ok(err) <span class="comment">// success</span>
  })
})</code></pre></div><hr class=""></div><div class="item method private"><h3 id="schema_string_SchemaString-checkRequired"><a href="#schema_string_SchemaString-checkRequired">SchemaString#checkRequired(<code>value</code>)</a></h3><p>Check required</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaString.prototype.checkRequired = <span class="function"><span class="keyword">function</span> <span class="title">checkRequired</span> <span class="params">(value)</span> {</span>
  <span class="keyword">if</span> (SchemaType._isRef(<span class="keyword">this</span>, value, <span class="literal">true</span>)) {
    <span class="keyword">return</span> <span class="literal">null</span> != value;
  } <span class="keyword">else</span> {
    <span class="keyword">return</span> (value <span class="keyword">instanceof</span> String || <span class="keyword">typeof</span> value == <span class="string">'string'</span>) &amp;&amp; value.length;
  }
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>value</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>, <a href="#null">null</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/undefined">undefined</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_string_SchemaString-cast"><a href="#schema_string_SchemaString-cast">SchemaString#cast()</a></h3><p>Casts to String</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaString.prototype.cast = <span class="function"><span class="keyword">function</span> <span class="params">(value, scope, init)</span> {</span>
  <span class="keyword">if</span> (SchemaType._isRef(<span class="keyword">this</span>, value, init)) <span class="keyword">return</span> value;
  <span class="keyword">if</span> (value === <span class="literal">null</span>) <span class="keyword">return</span> value;
  <span class="keyword">if</span> (<span class="string">'undefined'</span> !== <span class="keyword">typeof</span> value &amp;&amp; value.toString) <span class="keyword">return</span> value.toString();
  <span class="keyword">throw</span> <span class="keyword">new</span> CastError(<span class="string">'string'</span>, value);
};</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schema_string_SchemaString-castForQuery"><a href="#schema_string_SchemaString-castForQuery">SchemaString#castForQuery(<code>$conditional</code>, <code>[val]</code>)</a></h3><p>Casts contents for queries.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaString.prototype.castForQuery = <span class="function"><span class="keyword">function</span> <span class="params">($conditional, val)</span> {</span>
  <span class="keyword">var</span> handler;
  <span class="keyword">if</span> (arguments.length === <span class="number">2</span>) {
    handler = <span class="keyword">this</span>.$conditionalHandlers[$conditional];
    <span class="keyword">if</span> (!handler)
      <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">"Can't use "</span> + $conditional + <span class="string">" with String."</span>);
    <span class="keyword">return</span> handler.call(<span class="keyword">this</span>, val);
  } <span class="keyword">else</span> {
    val = $conditional;
    <span class="keyword">if</span> (val <span class="keyword">instanceof</span> RegExp) <span class="keyword">return</span> val;
    <span class="keyword">return</span> <span class="keyword">this</span>.cast(val);
  }
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>$conditional</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>[val]</code><span class="types"> &lt;<a href="#any">any</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div></li><li class="module "><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/schema.js" id="schema-js">schema.js</a><div class="item method public"><h3 id="schema_Schema"><a href="#schema_Schema">Schema(<code>definition</code>)</a></h3><p>Schema constructor.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">Schema</span> <span class="params">(obj, options)</span> {</span>
  <span class="keyword">if</span> (!(<span class="keyword">this</span> <span class="keyword">instanceof</span> Schema))
    <span class="keyword">return</span> <span class="keyword">new</span> Schema(obj, options);

  <span class="keyword">this</span>.paths = {};
  <span class="keyword">this</span>.subpaths = {};
  <span class="keyword">this</span>.virtuals = {};
  <span class="keyword">this</span>.nested = {};
  <span class="keyword">this</span>.inherits = {};
  <span class="keyword">this</span>.callQueue = [];
  <span class="keyword">this</span>._indexes = [];
  <span class="keyword">this</span>.methods = {};
  <span class="keyword">this</span>.statics = {};
  <span class="keyword">this</span>.tree = {};
  <span class="keyword">this</span>._requiredpaths = <span class="literal">undefined</span>;

  <span class="keyword">this</span>.options = <span class="keyword">this</span>.defaultOptions(options);

  <span class="comment">// build paths</span>
  <span class="keyword">if</span> (obj) {
    <span class="keyword">this</span>.add(obj);
  }

  <span class="comment">// ensure the documents get an auto _id unless disabled</span>
  <span class="keyword">var</span> auto_id = !<span class="keyword">this</span>.paths[<span class="string">'_id'</span>] &amp;&amp; (!<span class="keyword">this</span>.options.noId &amp;&amp; <span class="keyword">this</span>.options._id);
  <span class="keyword">if</span> (auto_id) {
    <span class="keyword">this</span>.add({ _id: {type: Schema.ObjectId, auto: <span class="literal">true</span>} });
  }

  <span class="comment">// ensure the documents receive an id getter unless disabled</span>
  <span class="keyword">var</span> autoid = !<span class="keyword">this</span>.paths[<span class="string">'id'</span>] &amp;&amp; (!<span class="keyword">this</span>.options.noVirtualId &amp;&amp; <span class="keyword">this</span>.options.id);
  <span class="keyword">if</span> (autoid) {
    <span class="keyword">this</span>.virtual(<span class="string">'id'</span>).get(idGetter);
  }

  <span class="comment">// versioning not directly added to schema b/c we only want</span>
  <span class="comment">// it in the top level document, not embedded ones.</span>
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>definition</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="http://nodejs.org/api/events.html#events_class_events_eventemitter" title="NodeJS EventEmitter">NodeJS EventEmitter</a></li></ul></div><div class="events"><h4>Events:</h4><ul><li><p><code>init</code>: Emitted after the schema is compiled into a <code>Model</code>.</p></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code><span class="keyword">var</span> child = <span class="keyword">new</span> Schema({ name: String });
<span class="keyword">var</span> schema = <span class="keyword">new</span> Schema({ name: String, age: Number, children: [child] });
<span class="keyword">var</span> Tree = mongoose.model(<span class="string">'Tree'</span>, schema);

<span class="comment">// setting schema options</span>
<span class="keyword">new</span> Schema({ name: String }, { _id: <span class="literal">false</span>, autoIndex: <span class="literal">false</span> })</code></pre>

<h4>Options:</h4>

<ul>
<li><a href="./guide.html#safe">safe</a>: bool - defaults to true.</li>
<li><a href="./guide.html#read">read</a>: string</li>
<li><a href="./guide.html#strict">strict</a>: bool - defaults to true</li>
<li><a href="./guide.html#capped">capped</a>: bool - defaults to false</li>
<li><a href="./guide.html#versionKey">versionKey</a>: bool - defaults to "__v"</li>
<li><a href="./guide.html#shardKey">shardKey</a>: bool - defaults to <code>null</code></li>
<li><a href="./guide.html#autoIndex">autoIndex</a>: bool - defaults to true</li>
<li><a href="./guide.html#_id">_id</a>: bool - defaults to true</li>
<li><a href="./guide.html#id">id</a>: bool - defaults to true</li>
<li><a href="./guide.html#toObject">toObject</a> - object - no default</li>
<li><a href="./guide.html#toJSON">toJSON</a> - object - no default</li>
<li><code>minimize</code>: bool - controls <a href="#document_Document-toObject">document#toObject</a> behavior when called manually - defaults to true</li>
</ul>

<h4>Note:</h4>

<p><em>When nesting schemas, (<code>children</code> in the example above), always declare the child schema first before passing it into is parent.</em></p></div><hr class=""></div><div class="item method private"><h3 id="schema_Schema-defaultOptions"><a href="#schema_Schema-defaultOptions">Schema#defaultOptions(<code>options</code>)</a></h3><p>Returns default options for this schema, merged with <code>options</code>.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Schema.prototype.defaultOptions = <span class="function"><span class="keyword">function</span> <span class="params">(options)</span> {</span>
  options = utils.options({
      safe: <span class="literal">true</span>
    , strict: <span class="literal">true</span>
    , capped: <span class="literal">false</span> <span class="comment">// { size, max, autoIndexId }</span>
    , versionKey: <span class="string">'__v'</span>
    , minimize: <span class="literal">true</span>
    , autoIndex: <span class="literal">true</span>
    , shardKey: <span class="literal">null</span>
    , read: <span class="literal">null</span>
    <span class="comment">// the following are only applied at construction time</span>
    , noId: <span class="literal">false</span> <span class="comment">// deprecated, use { _id: false }</span>
    , _id: <span class="literal">true</span>
    , noVirtualId: <span class="literal">false</span> <span class="comment">// deprecated, use { id: false }</span>
    , id: <span class="literal">true</span>
  }, options);

  <span class="keyword">if</span> (options.read)
    options.read = utils.readPref(options.read);

  <span class="keyword">return</span> options;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>options</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="schema_Schema-add"><a href="#schema_Schema-add">Schema#add(<code>obj</code>, <code>prefix</code>)</a></h3><p>Adds key path / schema type pairs to this schema.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Schema.prototype.add = <span class="function"><span class="keyword">function</span> <span class="title">add</span> <span class="params">(obj, prefix)</span> {</span>
  prefix = prefix || <span class="string">''</span>;
  <span class="keyword">for</span> (<span class="keyword">var</span> i <span class="keyword">in</span> obj) {
    <span class="keyword">if</span> (<span class="literal">null</span> == obj[i]) {
      <span class="keyword">throw</span> <span class="keyword">new</span> TypeError(<span class="string">'Invalid value for schema path `'</span>+ prefix + i +<span class="string">'`'</span>);
    }

    <span class="keyword">if</span> (obj[i].constructor.name == <span class="string">'Object'</span> &amp;&amp; (!obj[i].type || obj[i].type.type)) {
      <span class="keyword">if</span> (Object.keys(obj[i]).length) {
        <span class="comment">// nested object { last: { name: String }}</span>
        <span class="keyword">this</span>.nested[prefix + i] = <span class="literal">true</span>;
        <span class="keyword">this</span>.add(obj[i], prefix + i + <span class="string">'.'</span>);
      }
      <span class="keyword">else</span>
        <span class="keyword">this</span>.path(prefix + i, obj[i]); <span class="comment">// mixed type</span>
    } <span class="keyword">else</span>
      <span class="keyword">this</span>.path(prefix + i, obj[i]);
  }
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>obj</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>prefix</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code><span class="keyword">var</span> ToySchema = <span class="keyword">new</span> Schema;
ToySchema.add({ name: <span class="string">'string'</span>, color: <span class="string">'string'</span>, price: <span class="string">'number'</span> });</code></pre></div><hr class=""></div><div class="item method public"><h3 id="schema_Schema-path"><a href="#schema_Schema-path">Schema#path(<code>path</code>, <code>constructor</code>)</a></h3><p>Gets/sets schema paths.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Schema.prototype.path = <span class="function"><span class="keyword">function</span> <span class="params">(path, obj)</span> {</span>
  <span class="keyword">if</span> (obj == <span class="literal">undefined</span>) {
    <span class="keyword">if</span> (<span class="keyword">this</span>.paths[path]) <span class="keyword">return</span> <span class="keyword">this</span>.paths[path];
    <span class="keyword">if</span> (<span class="keyword">this</span>.subpaths[path]) <span class="keyword">return</span> <span class="keyword">this</span>.subpaths[path];

    <span class="comment">// subpaths?</span>
    <span class="keyword">return</span> <span class="regexp">/\.\d+\.?$/</span>.test(path)
      ? getPositionalPath(<span class="keyword">this</span>, path)
      : <span class="literal">undefined</span>;
  }

  <span class="comment">// some path names conflict with document methods</span>
  <span class="keyword">if</span> (reserved[path]) {
    <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">"`"</span> + path + <span class="string">"` may not be used as a schema pathname"</span>);
  }

  <span class="comment">// update the tree</span>
  <span class="keyword">var</span> subpaths = path.split(<span class="regexp">/\./</span>)
    , last = subpaths.pop()
    , branch = <span class="keyword">this</span>.tree;

  subpaths.forEach(<span class="keyword">function</span>(path) {
    <span class="keyword">if</span> (!branch[path]) branch[path] = {};
    branch = branch[path];
  });

  branch[last] = utils.clone(obj);

  <span class="keyword">this</span>.paths[path] = Schema.interpretAsType(path, obj);
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>constructor</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="description"><p>Sets a path (if arity 2)<br />Gets a path (if arity 1)</p>

<h4>Example</h4>

<pre><code>schema.path(<span class="string">'name'</span>) <span class="comment">// returns a SchemaType</span>
schema.path(<span class="string">'name'</span>, Number) <span class="comment">// changes the schemaType of `name` to Number</span></code></pre></div><hr class=""></div><div class="item method public"><h3 id="schema_Schema-eachPath"><a href="#schema_Schema-eachPath">Schema#eachPath(<code>fn</code>)</a></h3><p>Iterates the schemas paths similar to Array#forEach.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Schema.prototype.eachPath = <span class="function"><span class="keyword">function</span> <span class="params">(fn)</span> {</span>
  <span class="keyword">var</span> keys = Object.keys(<span class="keyword">this</span>.paths)
    , len = keys.length;

  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; len; ++i) {
    fn(keys[i], <span class="keyword">this</span>.paths[keys[i]]);
  }

  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>fn</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span>callback function</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#schema_Schema">Schema</a>&gt; </span><span>this</span></li></ul></div><div class="description"><p>The callback is passed the pathname and schemaType as arguments on each iteration.</p></div><hr class=""></div><div class="item method public"><h3 id="schema_Schema-requiredPaths"><a href="#schema_Schema-requiredPaths">Schema#requiredPaths()</a></h3><p>Returns an Array of path strings that are required by this schema.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Schema.prototype.requiredPaths = <span class="function"><span class="keyword">function</span> <span class="title">requiredPaths</span> <span class="params">()</span> {</span>
  <span class="keyword">if</span> (<span class="keyword">this</span>._requiredpaths) <span class="keyword">return</span> <span class="keyword">this</span>._requiredpaths;

  <span class="keyword">var</span> paths = Object.keys(<span class="keyword">this</span>.paths)
    , i = paths.length
    , ret = [];

  <span class="keyword">while</span> (i--) {
    <span class="keyword">var</span> path = paths[i];
    <span class="keyword">if</span> (<span class="keyword">this</span>.paths[path].isRequired) ret.push(path);
  }

  <span class="keyword">return</span> <span class="keyword">this</span>._requiredpaths = ret;
}</code></pre></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array">Array</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="schema_Schema-pathType"><a href="#schema_Schema-pathType">Schema#pathType(<code>path</code>)</a></h3><p>Returns the pathType of <code>path</code> for this schema.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Schema.prototype.pathType = <span class="function"><span class="keyword">function</span> <span class="params">(path)</span> {</span>
  <span class="keyword">if</span> (path <span class="keyword">in</span> <span class="keyword">this</span>.paths) <span class="keyword">return</span> <span class="string">'real'</span>;
  <span class="keyword">if</span> (path <span class="keyword">in</span> <span class="keyword">this</span>.virtuals) <span class="keyword">return</span> <span class="string">'virtual'</span>;
  <span class="keyword">if</span> (path <span class="keyword">in</span> <span class="keyword">this</span>.nested) <span class="keyword">return</span> <span class="string">'nested'</span>;
  <span class="keyword">if</span> (path <span class="keyword">in</span> <span class="keyword">this</span>.subpaths) <span class="keyword">return</span> <span class="string">'real'</span>;

  <span class="keyword">if</span> (<span class="regexp">/\.\d+\.?/</span>.test(path) &amp;&amp; getPositionalPath(<span class="keyword">this</span>, path)) {
    <span class="keyword">return</span> <span class="string">'real'</span>;
  } <span class="keyword">else</span> {
    <span class="keyword">return</span> <span class="string">'adhocOrUndefined'</span>
  }
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li></ul></div><div class="description"><p>Given a path, returns whether it is a real, virtual, nested, or ad-hoc/undefined path.</p></div><hr class=""></div><div class="item method private"><h3 id="schema_Schema-queue"><a href="#schema_Schema-queue">Schema#queue(<code>name</code>, <code>args</code>)</a></h3><p>Adds a method call to the queue.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Schema.prototype.queue = <span class="keyword">function</span>(name, args){
  <span class="keyword">this</span>.callQueue.push([name, args]);
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>name</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>name of the document method to call later</span></li><li><code>args</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array">Array</a>&gt; </span><span>arguments to pass to the method</span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="schema_Schema-pre"><a href="#schema_Schema-pre">Schema#pre(<code>method</code>, <code>callback</code>)</a></h3><p>Defines a pre hook for the document.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Schema.prototype.pre = <span class="keyword">function</span>(){
  <span class="keyword">return</span> <span class="keyword">this</span>.queue(<span class="string">'pre'</span>, arguments);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>method</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>callback</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3" title="hooks.js">hooks.js</a></li></ul></div><div class="description"><h4>Example</h4>

<pre><code><span class="keyword">var</span> toySchema = <span class="keyword">new</span> Schema(..);

toySchema.pre(<span class="string">'save'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(next)</span> {</span>
  <span class="keyword">if</span> (!<span class="keyword">this</span>.created) <span class="keyword">this</span>.created = <span class="keyword">new</span> Date;
  next();
})

toySchema.pre(<span class="string">'validate'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(next)</span> {</span>
  <span class="keyword">if</span> (<span class="keyword">this</span>.name != <span class="string">'Woody'</span>) <span class="keyword">this</span>.name = <span class="string">'Woody'</span>;
  next();
})</code></pre></div><hr class=""></div><div class="item method public"><h3 id="schema_Schema-post"><a href="#schema_Schema-post">Schema#post(<code>method</code>, <code>fn</code>)</a></h3><p>Defines a post hook for the document.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Schema.prototype.post = <span class="keyword">function</span>(method, fn){
  <span class="keyword">return</span> <span class="keyword">this</span>.queue(<span class="string">'on'</span>, arguments);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>method</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>name of the method to hook</span></li><li><code>fn</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span>callback</span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3" title="hooks.js">hooks.js</a></li></ul></div><div class="description"><p>Post hooks fire <code>on</code> the event emitted from document instances of Models compiled from this schema.</p>

<pre><code><span class="keyword">var</span> schema = <span class="keyword">new</span> Schema(..);
schema.post(<span class="string">'save'</span>, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  console.log(<span class="string">'this fired after a document was saved'</span>);
});

<span class="keyword">var</span> Model = mongoose.model(<span class="string">'Model'</span>, schema);

<span class="keyword">var</span> m = <span class="keyword">new</span> Model(..);
m.save(<span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
  console.log(<span class="string">'this fires after the `post` hook'</span>);
});</code></pre></div><hr class=""></div><div class="item method public"><h3 id="schema_Schema-plugin"><a href="#schema_Schema-plugin">Schema#plugin(<code>plugin</code>, <code>opts</code>)</a></h3><p>Registers a plugin for this schema.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Schema.prototype.plugin = <span class="function"><span class="keyword">function</span> <span class="params">(fn, opts)</span> {</span>
  fn(<span class="keyword">this</span>, opts);
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>plugin</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span>callback</span></li><li><code>opts</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="plugins" title="plugins">plugins</a></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="schema_Schema-method"><a href="#schema_Schema-method">Schema#method(<code>method</code>, <code>[fn]</code>)</a></h3><p>Adds an instance method to documents constructed from Models compiled from this schema.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Schema.prototype.method = <span class="function"><span class="keyword">function</span> <span class="params">(name, fn)</span> {</span>
  <span class="keyword">if</span> (<span class="string">'string'</span> != <span class="keyword">typeof</span> name)
    <span class="keyword">for</span> (<span class="keyword">var</span> i <span class="keyword">in</span> name)
      <span class="keyword">this</span>.methods[i] = name[i];
  <span class="keyword">else</span>
    <span class="keyword">this</span>.methods[name] = fn;
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>method</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>name</span></li><li><code>[fn]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="description"><h4>Example</h4>

<pre><code><span class="keyword">var</span> schema = kittySchema = <span class="keyword">new</span> Schema(..);

schema.methods.meow = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  console.log(<span class="string">'meeeeeoooooooooooow'</span>);
})

<span class="keyword">var</span> Kitty = mongoose.model(<span class="string">'Kitty'</span>, schema);

<span class="keyword">var</span> fizz = <span class="keyword">new</span> Kitty;
fizz.meow(); <span class="comment">// meeeeeooooooooooooow</span></code></pre>

<p>If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods.</p>

<pre><code>schema.method({
    purr: <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>}
  , scratch: <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>}
});

<span class="comment">// later</span>
fizz.purr();
fizz.scratch();</code></pre></div><hr class=""></div><div class="item method public"><h3 id="schema_Schema-static"><a href="#schema_Schema-static">Schema#static(<code>name</code>, <code>fn</code>)</a></h3><p>Adds static "class" methods to Models compiled from this schema.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Schema.prototype.static = <span class="keyword">function</span>(name, fn) {
  <span class="keyword">if</span> (<span class="string">'string'</span> != <span class="keyword">typeof</span> name)
    <span class="keyword">for</span> (<span class="keyword">var</span> i <span class="keyword">in</span> name)
      <span class="keyword">this</span>.statics[i] = name[i];
  <span class="keyword">else</span>
    <span class="keyword">this</span>.statics[name] = fn;
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>name</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>fn</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="description"><h4>Example</h4>

<pre><code><span class="keyword">var</span> schema = <span class="keyword">new</span> Schema(..);
schema.static(<span class="string">'findByName'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(name, callback)</span> {</span>
  <span class="keyword">return</span> <span class="keyword">this</span>.find({ name: name }, callback);
});

<span class="keyword">var</span> Drink = mongoose.model(<span class="string">'Drink'</span>, schema);
Drink.findByName(<span class="string">'sanpellegrino'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(err, drinks)</span> {</span>
  <span class="comment">//</span>
});</code></pre>

<p>If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics.</p></div><hr class=""></div><div class="item method public"><h3 id="schema_Schema-index"><a href="#schema_Schema-index">Schema#index(<code>fields</code>, <code>[options]</code>)</a></h3><p>Defines an index (most likely compound) for this schema.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Schema.prototype.index = <span class="function"><span class="keyword">function</span> <span class="params">(fields, options)</span> {</span>
  options || (options = {});

  <span class="keyword">if</span> (options.expires)
    utils.expires(options);

  <span class="keyword">this</span>._indexes.push([fields, options]);
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>fields</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[options]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="description"><h4>Example</h4>

<pre><code>schema.index({ first: <span class="number">1</span>, last: -<span class="number">1</span> })</code></pre></div><hr class=""></div><div class="item method public"><h3 id="schema_Schema-set"><a href="#schema_Schema-set">Schema#set(<code>key</code>, <code>[value]</code>)</a></h3><p>Sets/gets a schema option.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Schema.prototype.set = <span class="function"><span class="keyword">function</span> <span class="params">(key, value, tags)</span> {</span>
  <span class="keyword">if</span> (arguments.length == <span class="number">1</span>)
    <span class="keyword">return</span> <span class="keyword">this</span>.options[key];

  <span class="keyword">this</span>.options[key] = <span class="string">'read'</span> == key
    ? utils.readPref(value, tags)
    : value;

  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>key</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>option name</span></li><li><code>[value]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>if not passed, the current option value is returned</span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="schema_Schema-indexes"><a href="#schema_Schema-indexes">Schema#indexes()</a></h3><p>Compiles indexes from fields and schema-level indexes</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Schema.prototype.indexes = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">var</span> indexes = []
    , seenSchemas = [];

  collectIndexes(<span class="keyword">this</span>);

  <span class="keyword">return</span> indexes;

  <span class="function"><span class="keyword">function</span> <span class="title">collectIndexes</span> <span class="params">(schema, prefix)</span> {</span>
    <span class="keyword">if</span> (~seenSchemas.indexOf(schema)) <span class="keyword">return</span>;
    seenSchemas.push(schema);

    <span class="keyword">var</span> index;
    <span class="keyword">var</span> paths = schema.paths;
    prefix = prefix || <span class="string">''</span>;

    <span class="keyword">for</span> (<span class="keyword">var</span> i <span class="keyword">in</span> paths) {
      <span class="keyword">if</span> (paths[i]) {
        <span class="keyword">if</span> (paths[i] <span class="keyword">instanceof</span> Types.DocumentArray) {
          collectIndexes(paths[i].schema, i + <span class="string">'.'</span>);
        } <span class="keyword">else</span> {
          index = paths[i]._index;

          <span class="keyword">if</span> (index !== <span class="literal">false</span> &amp;&amp; index !== <span class="literal">null</span>){
            <span class="keyword">var</span> field = {};
            field[prefix + i] = <span class="string">'2d'</span> === index ? index : <span class="number">1</span>;
            <span class="keyword">var</span> options = <span class="string">'Object'</span> === index.constructor.name ? index : {};
            <span class="keyword">if</span> (!(<span class="string">'background'</span> <span class="keyword">in</span> options)) options.background = <span class="literal">true</span>;
            indexes.push([field, options]);
          }
        }
      }
    }

    <span class="keyword">if</span> (prefix) {
      fixSubIndexPaths(schema, prefix);
    } <span class="keyword">else</span> {
      schema._indexes.forEach(<span class="function"><span class="keyword">function</span> <span class="params">(index)</span> {</span>
        <span class="keyword">if</span> (!(<span class="string">'background'</span> <span class="keyword">in</span> index[<span class="number">1</span>])) index[<span class="number">1</span>].background = <span class="literal">true</span>;
      });
      indexes = indexes.concat(schema._indexes);
    }
  }</code></pre></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="schema_Schema-virtual"><a href="#schema_Schema-virtual">Schema#virtual(<code>name</code>, <code>[options]</code>)</a></h3><p>Creates a virtual type with the given name.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Schema.prototype.virtual = <span class="function"><span class="keyword">function</span> <span class="params">(name, options)</span> {</span>
  <span class="keyword">var</span> virtuals = <span class="keyword">this</span>.virtuals;
  <span class="keyword">var</span> parts = name.split(<span class="string">'.'</span>);
  <span class="keyword">return</span> virtuals[name] = parts.reduce(<span class="function"><span class="keyword">function</span> <span class="params">(mem, part, i)</span> {</span>
    mem[part] || (mem[part] = (i === parts.length-<span class="number">1</span>)
                            ? <span class="keyword">new</span> VirtualType(options, name)
                            : {});
    <span class="keyword">return</span> mem[part];
  }, <span class="keyword">this</span>.tree);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>name</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>[options]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#virtualtype_VirtualType">VirtualType</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="schema_Schema-virtualpath"><a href="#schema_Schema-virtualpath">Schema#virtualpath(<code>name</code>)</a></h3><p>Returns the virtual type with the given <code>name</code>.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Schema.prototype.virtualpath = <span class="function"><span class="keyword">function</span> <span class="params">(name)</span> {</span>
  <span class="keyword">return</span> <span class="keyword">this</span>.virtuals[name];
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>name</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#virtualtype_VirtualType">VirtualType</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method private"><h3 id="schema_Schema-namedScope"><a href="#schema_Schema-namedScope">Schema#namedScope()</a></h3><p>These still haven't been fixed. Once they're working we'll make them public again.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Schema.prototype.namedScope = <span class="function"><span class="keyword">function</span> <span class="params">(name, fn)</span> {</span>
  <span class="keyword">var</span> namedScopes = <span class="keyword">this</span>.namedScopes || (<span class="keyword">this</span>.namedScopes = <span class="keyword">new</span> NamedScope)
    , newScope = Object.create(namedScopes)
    , allScopes = namedScopes.scopesByName || (namedScopes.scopesByName = {});
  allScopes[name] = newScope;
  newScope.name = name;
  newScope.block = fn;
  newScope.query = <span class="keyword">new</span> Query();
  newScope.decorate(namedScopes, {
    block0: <span class="function"><span class="keyword">function</span> <span class="params">(block)</span> {</span>
      <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
        block.call(<span class="keyword">this</span>.query);
        <span class="keyword">return</span> <span class="keyword">this</span>;
      };
    },
    blockN: <span class="function"><span class="keyword">function</span> <span class="params">(block)</span> {</span>
      <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
        block.apply(<span class="keyword">this</span>.query, arguments);
        <span class="keyword">return</span> <span class="keyword">this</span>;
      };
    },
    basic: <span class="function"><span class="keyword">function</span> <span class="params">(query)</span> {</span>
      <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
        <span class="keyword">this</span>.query.find(query);
        <span class="keyword">return</span> <span class="keyword">this</span>;
      };
    }
  });
  <span class="keyword">return</span> newScope;
};</code></pre></div><div class="description"></div><hr class="private"></div><div class="item static public"><h3 id="schema_Schema-reserved"><a href="#schema_Schema-reserved">Schema.reserved</a></h3><p>Reserved document keys.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Schema.reserved = Object.create(<span class="literal">null</span>);
<span class="keyword">var</span> reserved = Schema.reserved;
reserved.on =
reserved.db =
reserved.init =
reserved.isNew =
reserved.errors =
reserved.schema =
reserved.options =
reserved.modelName =
reserved.collection = <span class="number">1</span>;</code></pre></div><p>Keys in this object are names that are rejected in schema declarations b/c they conflict with mongoose functionality. Using these key name will throw an error.</p>

<pre><code>on, db, init, isNew, errors, schema, options, modelName, collection</code></pre><hr class=""></div><div class="item static private"><h3 id="schema_Schema-interpretAsType"><a href="#schema_Schema-interpretAsType">Schema.interpretAsType(<code>path</code>, <code>obj</code>)</a></h3><p>Converts type arguments into Mongoose Types.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Schema.interpretAsType = function (path, obj) {
  if (obj.constructor.name != 'Object')
    obj = { type: obj };

  // Get the type making sure to allow keys named "type"
  // and default to mixed if not specified.
  // { type: { type: String, default: 'freshcut' } }
  var type = obj.type &amp;&amp; !obj.type.type
    ? obj.type
    : {};

  if ('Object' == type.constructor.name || 'mixed' == type) {
    return new Types.Mixed(path, obj);
  }

  if (Array.isArray(type) || Array == type || 'array' == type) {
    // if it was specified through { type } look for `cast`
    var cast = (Array == type || 'array' == type)
      ? obj.cast
      : type[0];

    if (cast instanceof Schema) {
      return new Types.DocumentArray(path, cast, obj);
    }

    if ('string' == typeof cast) {
      cast = Types[cast.charAt(0).toUpperCase() + cast.substring(1)];
    } else if (cast &amp;&amp; (!cast.type || cast.type.type)
                    &amp;&amp; 'Object' == cast.constructor.name
                    &amp;&amp; Object.keys(cast).length) {
      return new Types.DocumentArray(path, new Schema(cast), obj);
    }

    return new Types.Array(path, cast || Types.Mixed, obj);
  }

  var name = 'string' == typeof type
    ? type
    : type.name;

  if (name) {
    name = name.charAt(0).toUpperCase() + name.substring(1);
  }

  if (undefined == Types[name]) {
    throw new TypeError('Undefined type at `' + path +
        '`
  Did you try nesting Schemas? ' +
        'You can only nest using refs or arrays.');
  }

  return new Types[name](path, obj);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>obj</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>constructor</span></li></ul></div><hr class="private"></div><div class="item static public"><h3 id="schema_Schema-Types"><a href="#schema_Schema-Types">Schema.Types</a></h3><p>The various Mongoose Schema Types.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">Schema.Types = require(<span class="string">'./schema/index'</span>);</code></pre></div><h4>Example:</h4>

<h4>Example:</h4>

<pre><code><span class="keyword">var</span> mongoose = require(<span class="string">'mongoose'</span>);
<span class="keyword">var</span> ObjectId = mongoose.Schema.Types.ObjectId;</code></pre>

<h4>Types:</h4>

<ul>
<li>String</li>
<li>Number</li>
<li>Boolean | Bool</li>
<li>Array</li>
<li>Buffer</li>
<li>Date</li>
<li>ObjectId | Oid</li>
<li>Mixed</li>
</ul>

<p>Using this exposed access to the <code>Mixed</code> SchemaType, we can use them in our schema.</p>

<pre><code><span class="keyword">var</span> Mixed = mongoose.Schema.Types.Mixed;
<span class="keyword">new</span> mongoose.Schema({ _user: Mixed })</code></pre><hr class=""></div><div class="item property private"><h3 id="schema_Schema-tree"><a href="#schema_Schema-tree">Schema#<span>tree</span></a></h3><p>Schema as a tree</p>

<h4>Example:</h4>

<pre><code>{
    <span class="string">'_id'</span>     : ObjectId
  , <span class="string">'nested'</span>  : {
        <span class="string">'key'</span> : String
    }
}</code></pre><hr class="private"></div><div class="item property private"><h3 id="schema_Schema-paths"><a href="#schema_Schema-paths">Schema#<span>paths</span></a></h3><p>Schema as flat paths</p>

<h4>Example:</h4>

<pre><code>{
    <span class="string">'_id'</span>        : SchemaType,
  , <span class="string">'nested.key'</span> : SchemaType,
}</code></pre><hr class="private"></div></li><li class="module private"><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/schemadefault.js" id="schemadefault-js">schemadefault.js</a><div class="item property private"><h3 id="schemadefault_exports-system-profile"><a href="#schemadefault_exports-system-profile">exports#<span>system.profile</span></a></h3><p>Default model for querying the system.profiles collection.</p><hr class="private"></div></li><li class="module "><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/schematype.js" id="schematype-js">schematype.js</a><div class="item method public"><h3 id="schematype_SchemaType"><a href="#schematype_SchemaType">SchemaType(<code>path</code>, <code>[options]</code>, <code>[instance]</code>)</a></h3><p>SchemaType constructor</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">SchemaType</span> <span class="params">(path, options, instance)</span> {</span>
  <span class="keyword">this</span>.path = path;
  <span class="keyword">this</span>.instance = instance;
  <span class="keyword">this</span>.validators = [];
  <span class="keyword">this</span>.setters = [];
  <span class="keyword">this</span>.getters = [];
  <span class="keyword">this</span>.options = options;
  <span class="keyword">this</span>._index = <span class="literal">null</span>;
  <span class="keyword">this</span>.selected;

  <span class="keyword">for</span> (<span class="keyword">var</span> i <span class="keyword">in</span> options) <span class="keyword">if</span> (<span class="keyword">this</span>[i] &amp;&amp; <span class="string">'function'</span> == <span class="keyword">typeof</span> <span class="keyword">this</span>[i]) {
    <span class="comment">// { unique: true, index: true }</span>
    <span class="keyword">if</span> (<span class="string">'index'</span> == i &amp;&amp; <span class="keyword">this</span>._index) <span class="keyword">continue</span>;

    <span class="keyword">var</span> opts = Array.isArray(options[i])
      ? options[i]
      : [options[i]];

    <span class="keyword">this</span>[i].apply(<span class="keyword">this</span>, opts);
  }
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>[options]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>[instance]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="schematype_SchemaType-default"><a href="#schematype_SchemaType-default">SchemaType#default(<code>val</code>)</a></h3><p>Sets a default value for this SchemaType.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaType.prototype.<span class="keyword">default</span> = <span class="function"><span class="keyword">function</span> <span class="params">(val)</span> {</span>
  <span class="keyword">if</span> (<span class="number">1</span> === arguments.length) {
    <span class="keyword">this</span>.defaultValue = <span class="keyword">typeof</span> val === <span class="string">'function'</span>
      ? val
      : <span class="keyword">this</span>.cast(val);
    <span class="keyword">return</span> <span class="keyword">this</span>;
  } <span class="keyword">else</span> <span class="keyword">if</span> (arguments.length > <span class="number">1</span>) {
    <span class="keyword">this</span>.defaultValue = utils.args(arguments);
  }
  <span class="keyword">return</span> <span class="keyword">this</span>.defaultValue;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>, <a href="#any">any</a>&gt; </span><span>the default value</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#defaultValue">defaultValue</a>&gt; </span><span></span></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code><span class="keyword">var</span> schema = <span class="keyword">new</span> Schema({ n: { type: Number, <span class="keyword">default</span>: <span class="number">10</span> })
<span class="keyword">var</span> M = db.model(<span class="string">'M'</span>, schema)
<span class="keyword">var</span> m = <span class="keyword">new</span> M;
console.log(m.n) <span class="comment">// 10</span></code></pre>

<p>Defaults can be either <code>functions</code> which return the value to use as the default or the literal value itself. Either way, the value will be cast based on its schema type before being set during document creation.</p>

<h4>Example:</h4>

<pre><code><span class="comment">// values are cast:</span>
<span class="keyword">var</span> schema = <span class="keyword">new</span> Schema({ aNumber: Number, <span class="keyword">default</span>: <span class="string">"4.815162342"</span> })
<span class="keyword">var</span> M = db.model(<span class="string">'M'</span>, schema)
<span class="keyword">var</span> m = <span class="keyword">new</span> M;
console.log(m.aNumber) <span class="comment">// 4.815162342</span>

<span class="comment">// default unique objects for Mixed types:</span>
<span class="keyword">var</span> schema = <span class="keyword">new</span> Schema({ mixed: Schema.Types.Mixed });
schema.path(<span class="string">'mixed'</span>).<span class="keyword">default</span>(<span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">return</span> {};
});

<span class="comment">// if we don't use a function to return object literals for Mixed defaults,</span>
<span class="comment">// each document will receive a reference to the same object literal creating</span>
<span class="comment">// a "shared" object instance:</span>
<span class="keyword">var</span> schema = <span class="keyword">new</span> Schema({ mixed: Schema.Types.Mixed });
schema.path(<span class="string">'mixed'</span>).<span class="keyword">default</span>({});
<span class="keyword">var</span> M = db.model(<span class="string">'M'</span>, schema);
<span class="keyword">var</span> m1 = <span class="keyword">new</span> M;
m1.mixed.added = <span class="number">1</span>;
console.log(m1.mixed); <span class="comment">// { added: 1 }</span>
<span class="keyword">var</span> m2 = <span class="keyword">new</span> M;
console.log(m2.mixed); <span class="comment">// { added: 1 }</span></code></pre></div><hr class=""></div><div class="item method public"><h3 id="schematype_SchemaType-index"><a href="#schematype_SchemaType-index">SchemaType#index(<code>options</code>)</a></h3><p>Declares the index options for this schematype.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaType.prototype.index = <span class="function"><span class="keyword">function</span> <span class="params">(options)</span> {</span>
  <span class="keyword">this</span>._index = options;
  utils.expires(<span class="keyword">this</span>._index);
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>options</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#schematype_SchemaType">SchemaType</a>&gt; </span><span>this</span></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code><span class="keyword">var</span> s = <span class="keyword">new</span> Schema({ name: { type: String, index: <span class="literal">true</span> })
<span class="keyword">var</span> s = <span class="keyword">new</span> Schema({ name: { type: String, index: { unique: <span class="literal">true</span>, expires: <span class="string">'1d'</span> }})
Schema.path(<span class="string">'my.path'</span>).index(<span class="literal">true</span>);
Schema.path(<span class="string">'my.path'</span>).index({ expires: <span class="number">60</span> });
Schema.path(<span class="string">'my.path'</span>).index({ unique: <span class="literal">true</span>, sparse: <span class="literal">true</span> });</code></pre>

<h4>NOTE:</h4>

<p><em>Indexes are created in the background by default. Specify <code>background: false</code> to override.</em></p>

<p><a href="http://www.mongodb.org/display/DOCS/Indexes#Indexes-CompoundKeysIndexes">Direction doesn't matter for single key indexes</a></p></div><hr class=""></div><div class="item method public"><h3 id="schematype_SchemaType-unique"><a href="#schematype_SchemaType-unique">SchemaType#unique(<code>bool</code>)</a></h3><p>Declares an unique index.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaType.prototype.unique = <span class="function"><span class="keyword">function</span> <span class="params">(bool)</span> {</span>
  <span class="keyword">if</span> (!<span class="keyword">this</span>._index || <span class="string">'Object'</span> !== <span class="keyword">this</span>._index.constructor.name) {
    <span class="keyword">this</span>._index = {};
  }

  <span class="keyword">this</span>._index.unique = bool;
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>bool</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#schematype_SchemaType">SchemaType</a>&gt; </span><span>this</span></li></ul></div><div class="description"><h4>Examples:</h4>

<pre><code><span class="keyword">var</span> s = <span class="keyword">new</span> Schema({ name: { type: String, unique: <span class="literal">true</span> })
Schema.path(<span class="string">'name'</span>).index({ unique: <span class="literal">true</span> });</code></pre></div><hr class=""></div><div class="item method public"><h3 id="schematype_SchemaType-sparse"><a href="#schematype_SchemaType-sparse">SchemaType#sparse(<code>bool</code>)</a></h3><p>Declares a sparse index.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaType.prototype.sparse = <span class="function"><span class="keyword">function</span> <span class="params">(bool)</span> {</span>
  <span class="keyword">if</span> (!<span class="keyword">this</span>._index || <span class="string">'Object'</span> !== <span class="keyword">this</span>._index.constructor.name) {
    <span class="keyword">this</span>._index = {};
  }

  <span class="keyword">this</span>._index.sparse = bool;
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>bool</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#schematype_SchemaType">SchemaType</a>&gt; </span><span>this</span></li></ul></div><div class="description"><h4>Examples:</h4>

<pre><code><span class="keyword">var</span> s = <span class="keyword">new</span> Schema({ name: { type: String, sparse: <span class="literal">true</span> })
Schema.path(<span class="string">'name'</span>).index({ sparse: <span class="literal">true</span> });</code></pre></div><hr class=""></div><div class="item method public"><h3 id="schematype_SchemaType-expires"><a href="#schematype_SchemaType-expires">SchemaType#expires(<code>when</code>)</a></h3><p>Declares a TTL index (rounded to the nearest second) for <em>Date</em> types only.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaType.prototype.expires = <span class="function"><span class="keyword">function</span> <span class="params">(when)</span> {</span>
  <span class="keyword">if</span> (!<span class="keyword">this</span>._index || <span class="string">'Object'</span> !== <span class="keyword">this</span>._index.constructor.name) {
    <span class="keyword">this</span>._index = {};
  }

  <span class="keyword">this</span>._index.expires = when;
  utils.expires(<span class="keyword">this</span>._index);
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>when</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#schematype_SchemaType">SchemaType</a>&gt; </span><span>this</span></li></ul></div><div class="description"><p>This sets the <code>expiresAfterSeconds</code> index option available in MongoDB >= 2.1.2.<br />This index type is only compatible with Date types.</p>

<h4>Example:</h4>

<pre><code><span class="comment">// expire in 24 hours</span>
<span class="keyword">new</span> Schema({..}, { expires: <span class="number">60</span>*<span class="number">60</span>*<span class="number">24</span> });</code></pre>

<p><code>expires</code> utilizes the <code>ms</code> module from <a href="https://github.com/guille/">guille</a> allowing us to use a friendlier syntax:</p>

<h4>Example:</h4>

<pre><code><span class="comment">// expire in 24 hours</span>
<span class="keyword">new</span> Schema({..}, { expires: <span class="string">'24h'</span> });

<span class="comment">// expire in 1.5 hours</span>
<span class="keyword">new</span> Schema({..}, { expires: <span class="string">'1.5h'</span> });

<span class="comment">// expire in 7 days</span>
<span class="keyword">var</span> schema = <span class="keyword">new</span> Schema({..});
schema.expires(<span class="string">'7d'</span>);</code></pre></div><hr class=""></div><div class="item method public"><h3 id="schematype_SchemaType-set"><a href="#schematype_SchemaType-set">SchemaType#set(<code>fn</code>)</a></h3><p>Adds a setter to this schematype.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaType.prototype.set = <span class="function"><span class="keyword">function</span> <span class="params">(fn)</span> {</span>
  <span class="keyword">if</span> (<span class="string">'function'</span> != <span class="keyword">typeof</span> fn)
    <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">'A setter must be a function.'</span>);
  <span class="keyword">this</span>.setters.push(fn);
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>fn</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#schematype_SchemaType">SchemaType</a>&gt; </span><span>this</span></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code><span class="function"><span class="keyword">function</span> <span class="title">capitalize</span> <span class="params">(val)</span> {</span>
  <span class="keyword">if</span> (<span class="string">'string'</span> != <span class="keyword">typeof</span> val) val = <span class="string">''</span>;
  <span class="keyword">return</span> val.charAt(<span class="number">0</span>).toUpperCase() + val.substring(<span class="number">1</span>);
}

<span class="comment">// defining within the schema</span>
<span class="keyword">var</span> s = <span class="keyword">new</span> Schema({ name: { type: String, set: capitalize }})

<span class="comment">// or by retreiving its SchemaType</span>
<span class="keyword">var</span> s = <span class="keyword">new</span> Schema({ name: String })
s.path(<span class="string">'name'</span>).set(capitalize)</code></pre>

<p>Setters allow you to transform the data before it gets to the raw mongodb document and is set as a value on an actual key.</p>

<p>Suppose you are implementing user registration for a website. Users provide an email and password, which gets saved to mongodb. The email is a string that you will want to normalize to lower case, in order to avoid one email having more than one account -- e.g., otherwise, <a href='mailto:avenue@q.com'>avenue@q.com</a> can be registered for 2 accounts via <a href='mailto:avenue@q.com'>avenue@q.com</a> and <a href='mailto:AvEnUe@Q.CoM'>AvEnUe@Q.CoM</a>.</p>

<p>You can set up email lower case normalization easily via a Mongoose setter.</p>

<pre><code>function toLower (v) {
  return v.toLowerCase();
}

var UserSchema = new Schema({
  email: { type: String, set: toLower }
})

var User = db.model('User', UserSchema)

var user = new User({email: '<a href='mailto:AVENUE@Q.COM'>AVENUE@Q.COM</a>'})
console.log(user.email); // '<a href='mailto:avenue@q.com'>avenue@q.com</a>'

// or
var user = new User
user.email = '<a href='mailto:Avenue@Q.com'>Avenue@Q.com</a>'
console.log(user.email) // '<a href='mailto:avenue@q.com'>avenue@q.com</a>'
</code></pre>

<p>As you can see above, setters allow you to transform the data before it gets to the raw mongodb document and is set as a value on an actual key.</p>

<p><em>NOTE: we could have also just used the built-in <code>lowercase: true</code> SchemaType option instead of defining our own function.</em></p>

<pre><code><span class="keyword">new</span> Schema({ email: { type: String, lowercase: <span class="literal">true</span> }})</code></pre></div><hr class=""></div><div class="item method public"><h3 id="schematype_SchemaType-get"><a href="#schematype_SchemaType-get">SchemaType#get(<code>fn</code>)</a></h3><p>Adds a getter to this schematype.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaType.prototype.get = <span class="function"><span class="keyword">function</span> <span class="params">(fn)</span> {</span>
  <span class="keyword">if</span> (<span class="string">'function'</span> != <span class="keyword">typeof</span> fn)
    <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">'A getter must be a function.'</span>);
  <span class="keyword">this</span>.getters.push(fn);
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>fn</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#schematype_SchemaType">SchemaType</a>&gt; </span><span>this</span></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code><span class="function"><span class="keyword">function</span> <span class="title">dob</span> <span class="params">(val)</span> {</span>
  <span class="keyword">if</span> (!val) <span class="keyword">return</span> val;
  <span class="keyword">return</span> (val.getMonth() + <span class="number">1</span>) + <span class="string">"/"</span> + val.getDate() + <span class="string">"/"</span> + val.getFullYear();
}

<span class="comment">// defining within the schema</span>
<span class="keyword">var</span> s = <span class="keyword">new</span> Schema({ born: { type: Date, get: dob })

<span class="comment">// or by retreiving its SchemaType</span>
<span class="keyword">var</span> s = <span class="keyword">new</span> Schema({ born: Date })
s.path(<span class="string">'born'</span>).get(dob)</code></pre>

<p>Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see.</p>

<p>Suppose you are storing credit card numbers and you want to hide everything except the last 4 digits to the mongoose user. You can do so by defining a getter in the following way:</p>

<pre><code><span class="function"><span class="keyword">function</span> <span class="title">obfuscate</span> <span class="params">(cc)</span> {</span>
  <span class="keyword">return</span> <span class="string">'****-****-****-'</span> + cc.slice(cc.length-<span class="number">4</span>, cc.length);
}

<span class="keyword">var</span> AccountSchema = <span class="keyword">new</span> Schema({
  creditCardNumber: { type: String, get: obfuscate }
});

<span class="keyword">var</span> Account = db.model(<span class="string">'Account'</span>, AccountSchema);

Account.findById(id, <span class="function"><span class="keyword">function</span> <span class="params">(err, found)</span> {</span>
  console.log(found.creditCardNumber); <span class="comment">// '****-****-****-1234'</span>
});</code></pre></div><hr class=""></div><div class="item method public"><h3 id="schematype_SchemaType-validate"><a href="#schematype_SchemaType-validate">SchemaType#validate(<code>obj</code>, <code>[error]</code>)</a></h3><p>Adds validator(s) for this document path.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaType.prototype.validate = <span class="function"><span class="keyword">function</span> <span class="params">(obj, error)</span> {</span>
  <span class="keyword">if</span> (<span class="string">'function'</span> == <span class="keyword">typeof</span> obj || obj &amp;&amp; <span class="string">'RegExp'</span> === obj.constructor.name) {
    <span class="keyword">this</span>.validators.push([obj, error]);
    <span class="keyword">return</span> <span class="keyword">this</span>;
  }

  <span class="keyword">var</span> i = arguments.length
    , arg

  <span class="keyword">while</span> (i--) {
    arg = arguments[i];
    <span class="keyword">if</span> (!(arg &amp;&amp; <span class="string">'Object'</span> == arg.constructor.name)) {
      <span class="keyword">var</span> msg = <span class="string">'Invalid validator. Received ('</span> + <span class="keyword">typeof</span> arg + <span class="string">') '</span>
        + arg
        + <span class="string">'. See http://mongoosejs.com./api.html#schematype_SchemaType-validate'</span>;

      <span class="keyword">throw</span> <span class="keyword">new</span> Error(msg);
    }
    <span class="keyword">this</span>.validate(arg.validator, arg.msg);
  }

  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>obj</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/RegExp">RegExp</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>validator</span></li><li><code>[error]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>optional error message</span></li></ul></div><div class="description"><p>Validators must return <code>Boolean</code>. Returning false is interpreted as validation failure.</p>

<h4>Examples:</h4>

<pre><code><span class="function"><span class="keyword">function</span> <span class="title">validator</span> <span class="params">()</span> {</span> ... }

<span class="keyword">var</span> single = [validator, <span class="string">'failed'</span>]
<span class="keyword">new</span> Schema({ name: { type: String, validate: single }});

<span class="keyword">var</span> many = [
    { validator: validator, msg: <span class="string">'uh oh'</span> }
  , { validator: fn, msg: <span class="string">'failed'</span> }
]
<span class="keyword">new</span> Schema({ name: { type: String, validate: many }});

<span class="comment">// or utilizing SchemaType methods directly:</span>

<span class="keyword">var</span> schema = <span class="keyword">new</span> Schema({ name: <span class="string">'string'</span> });
schema.path(<span class="string">'name'</span>).validate(validator, <span class="string">'validation failed'</span>);</code></pre>

<h4>Asynchronous validation:</h4>

<p>Passing a validator function that receives two arguments tells mongoose that the validator is an asynchronous validator. The first arg passed is the value to validate, the second is an callback function that must be passed either <code>true</code> or <code>false</code> when validation is complete. Asynchronous validators open the door for retreiving other documents from the database first to validate against.</p>

<pre><code>schema.path(<span class="string">'name'</span>).validate(<span class="function"><span class="keyword">function</span> <span class="params">(value, respond)</span> {</span>
  doStuff(value, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
    ...
    respond(<span class="literal">false</span>); <span class="comment">// validation failed</span>
  })
 }, <span class="string">'my error type'</span>);</code></pre>

<p>Validation occurs <code>pre('save')</code> or whenever you manually execute <a href="#document_Document-validate">document#validate</a>.</p>

<p>If validation fails during <code>pre('save')</code> and no callback was passed to receive the error, an <code>error</code> event will be emitted on your Models associated db <a href="#connection_Connection">connection</a>, passing the validation error object along.</p>

<pre><code><span class="keyword">var</span> conn = mongoose.createConnection(..);
conn.on(<span class="string">'error'</span>, handleError);

<span class="keyword">var</span> Product = conn.model(<span class="string">'Product'</span>, yourSchema);
<span class="keyword">var</span> dvd = <span class="keyword">new</span> Product(..);
dvd.save(); <span class="comment">// emits error on the `conn` above</span></code></pre>

<p>If you desire handling these errors at the Model level, attach an <code>error</code> listener to your Model and the event will instead be emitted there.</p>

<pre><code><span class="comment">// registering an error listener on the Model lets us handle errors more locally</span>
Product.on(<span class="string">'error'</span>, handleError);</code></pre></div><hr class=""></div><div class="item method public"><h3 id="schematype_SchemaType-required"><a href="#schematype_SchemaType-required">SchemaType#required(<code>required</code>)</a></h3><p>Adds a required validator to this schematype.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaType.prototype.required = <span class="function"><span class="keyword">function</span> <span class="params">(required)</span> {</span>
  <span class="keyword">var</span> self = <span class="keyword">this</span>;

  <span class="function"><span class="keyword">function</span> <span class="title">__checkRequired</span> <span class="params">(v)</span> {</span>
    <span class="comment">// in here, `this` refers to the validating document.</span>
    <span class="comment">// no validation when this path wasn't selected in the query.</span>
    <span class="keyword">if</span> (<span class="string">'isSelected'</span> <span class="keyword">in</span> <span class="keyword">this</span> &amp;&amp;
        !<span class="keyword">this</span>.isSelected(self.path) &amp;&amp;
        !<span class="keyword">this</span>.isModified(self.path)) <span class="keyword">return</span> <span class="literal">true</span>;
    <span class="keyword">return</span> self.checkRequired(v);
  }

  <span class="keyword">if</span> (<span class="literal">false</span> === required) {
    <span class="keyword">this</span>.isRequired = <span class="literal">false</span>;
    <span class="keyword">this</span>.validators = <span class="keyword">this</span>.validators.filter(<span class="function"><span class="keyword">function</span> <span class="params">(v)</span> {</span>
      <span class="keyword">return</span> v[<span class="number">0</span>].name !== <span class="string">'__checkRequired'</span>;
    });
  } <span class="keyword">else</span> {
    <span class="keyword">this</span>.isRequired = <span class="literal">true</span>;
    <span class="keyword">this</span>.validators.push([__checkRequired, <span class="string">'required'</span>]);
  }

  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>required</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span>enable/disable the validator</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#schematype_SchemaType">SchemaType</a>&gt; </span><span>this</span></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code><span class="keyword">var</span> s = <span class="keyword">new</span> Schema({ born: { type: Date, required: <span class="literal">true</span> })
<span class="comment">// or</span>
Schema.path(<span class="string">'name'</span>).required(<span class="literal">true</span>);</code></pre></div><hr class=""></div><div class="item method private"><h3 id="schematype_SchemaType-getDefault"><a href="#schematype_SchemaType-getDefault">SchemaType#getDefault(<code>scope</code>, <code>init</code>)</a></h3><p>Gets the default value</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaType.prototype.getDefault = <span class="function"><span class="keyword">function</span> <span class="params">(scope, init)</span> {</span>
  <span class="keyword">var</span> ret = <span class="string">'function'</span> === <span class="keyword">typeof</span> <span class="keyword">this</span>.defaultValue
    ? <span class="keyword">this</span>.defaultValue.call(scope)
    : <span class="keyword">this</span>.defaultValue;

  <span class="keyword">if</span> (<span class="literal">null</span> !== ret &amp;&amp; <span class="literal">undefined</span> !== ret) {
    <span class="keyword">return</span> <span class="keyword">this</span>.cast(ret, scope, init);
  } <span class="keyword">else</span> {
    <span class="keyword">return</span> ret;
  }
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>scope</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>the scope which callback are executed</span></li><li><code>init</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schematype_SchemaType-applySetters"><a href="#schematype_SchemaType-applySetters">SchemaType#applySetters(<code>value</code>, <code>scope</code>, <code>init</code>)</a></h3><p>Applies setters</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaType.prototype.applySetters = <span class="function"><span class="keyword">function</span> <span class="params">(value, scope, init, priorVal)</span> {</span>
  <span class="keyword">if</span> (SchemaType._isRef(<span class="keyword">this</span>, value, init)) <span class="keyword">return</span> value;

  <span class="keyword">var</span> v = value
    , setters = <span class="keyword">this</span>.setters
    , len = setters.length

  <span class="keyword">if</span> (!len) {
    <span class="keyword">if</span> (<span class="literal">null</span> === v || <span class="literal">undefined</span> === v) <span class="keyword">return</span> v;
    <span class="keyword">return</span> init
      ? v <span class="comment">// if we just initialized we dont recast</span>
      : <span class="keyword">this</span>.cast(v, scope, init, priorVal)
  }

  <span class="keyword">while</span> (len--) {
    v = setters[len].call(scope, v, <span class="keyword">this</span>);
  }

  <span class="keyword">if</span> (<span class="literal">null</span> === v || <span class="literal">undefined</span> === v) <span class="keyword">return</span> v;

  <span class="comment">// do not cast until all setters are applied #665</span>
  v = <span class="keyword">this</span>.cast(v, scope, init, priorVal);

  <span class="keyword">return</span> v;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>value</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>scope</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>init</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="schematype_SchemaType-applyGetters"><a href="#schematype_SchemaType-applyGetters">SchemaType#applyGetters(<code>value</code>, <code>scope</code>)</a></h3><p>Applies getters to a value</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaType.prototype.applyGetters = <span class="function"><span class="keyword">function</span> <span class="params">(value, scope)</span> {</span>
  <span class="keyword">if</span> (SchemaType._isRef(<span class="keyword">this</span>, value, <span class="literal">true</span>)) <span class="keyword">return</span> value;

  <span class="keyword">var</span> v = value
    , getters = <span class="keyword">this</span>.getters
    , len = getters.length;

  <span class="keyword">if</span> (!len) {
    <span class="keyword">return</span> v;
  }

  <span class="keyword">while</span> (len--) {
    v = getters[len].call(scope, v, <span class="keyword">this</span>);
  }

  <span class="keyword">return</span> v;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>value</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>scope</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="schematype_SchemaType-select"><a href="#schematype_SchemaType-select">SchemaType#select(<code>val</code>)</a></h3><p>Sets default <code>select()</code> behavior for this path.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaType.prototype.select = <span class="function"><span class="keyword">function</span> <span class="title">select</span> <span class="params">(val)</span> {</span>
  <span class="keyword">this</span>.selected = !! val;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>val</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span></span></li></ul></div><div class="description"><p>Set to <code>true</code> if this path should always be included in the results, <code>false</code> if it should be excluded by default. This setting can be overridden at the query level.</p>

<h4>Example:</h4>

<pre><code>T = db.model(<span class="string">'T'</span>, <span class="keyword">new</span> Schema({ x: { type: String, select: <span class="literal">true</span> }}));
T.find(..); <span class="comment">// field x will always be selected ..</span>
<span class="comment">// .. unless overridden;</span>
T.find().select(<span class="string">'-x'</span>).exec(callback);</code></pre></div><hr class=""></div><div class="item method private"><h3 id="schematype_SchemaType-doValidate"><a href="#schematype_SchemaType-doValidate">SchemaType#doValidate(<code>value</code>, <code>callback</code>, <code>scope</code>)</a></h3><p>Performs a validation of <code>value</code> using the validators declared for this SchemaType.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaType.prototype.doValidate = <span class="function"><span class="keyword">function</span> <span class="params">(value, fn, scope)</span> {</span>
  <span class="keyword">var</span> err = <span class="literal">false</span>
    , path = <span class="keyword">this</span>.path
    , count = <span class="keyword">this</span>.validators.length;

  <span class="keyword">if</span> (!count) <span class="keyword">return</span> fn(<span class="literal">null</span>);

  <span class="function"><span class="keyword">function</span> <span class="title">validate</span> <span class="params">(val, msg)</span> {</span>
    <span class="keyword">if</span> (err) <span class="keyword">return</span>;
    <span class="keyword">if</span> (val === <span class="literal">undefined</span> || val) {
      --count || fn(<span class="literal">null</span>);
    } <span class="keyword">else</span> {
      fn(err = <span class="keyword">new</span> ValidatorError(path, msg));
    }
  }

  <span class="keyword">this</span>.validators.forEach(<span class="function"><span class="keyword">function</span> <span class="params">(v)</span> {</span>
    <span class="keyword">var</span> validator = v[<span class="number">0</span>]
      , message   = v[<span class="number">1</span>];

    <span class="keyword">if</span> (validator <span class="keyword">instanceof</span> RegExp) {
      validate(validator.test(value), message);
    } <span class="keyword">else</span> <span class="keyword">if</span> (<span class="string">'function'</span> === <span class="keyword">typeof</span> validator) {
      <span class="keyword">if</span> (<span class="number">2</span> === validator.length) {
        validator.call(scope, value, <span class="function"><span class="keyword">function</span> <span class="params">(val)</span> {</span>
          validate(val, message);
        });
      } <span class="keyword">else</span> {
        validate(validator.call(scope, value), message);
      }
    }
  });
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>value</code><span class="types"> &lt;<a href="#any">any</a>&gt; </span><span></span></li><li><code>callback</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li><li><code>scope</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item static private"><h3 id="schematype_SchemaType-_isRef"><a href="#schematype_SchemaType-_isRef">SchemaType._isRef(<code>self</code>, <code>value</code>, <code>init</code>)</a></h3><p>Determines if value is a valid Reference.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">SchemaType._isRef = <span class="function"><span class="keyword">function</span> <span class="params">(self, value, init)</span> {</span>
  <span class="keyword">if</span> (init &amp;&amp; self.options &amp;&amp; self.options.ref) {
    <span class="keyword">if</span> (<span class="literal">null</span> == value) <span class="keyword">return</span> <span class="literal">true</span>;
    <span class="keyword">if</span> (value._id &amp;&amp; value._id.constructor.name === self.instance) <span class="keyword">return</span> <span class="literal">true</span>;
  }

  <span class="keyword">return</span> <span class="literal">false</span>;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>self</code><span class="types"> &lt;<a href="#schematype_SchemaType">SchemaType</a>&gt; </span><span></span></li><li><code>value</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>init</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span></span></li></ul></div><hr class="private"></div></li><li class="module "><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/types/array.js" id="types-array-js">types/array.js</a><div class="item method private"><h3 id="types_array_MongooseArray"><a href="#types_array_MongooseArray">MongooseArray(<code>values</code>, <code>path</code>, <code>doc</code>)</a></h3><p>Mongoose Array constructor.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">MongooseArray</span> <span class="params">(values, path, doc)</span> {</span>
  <span class="keyword">var</span> arr = [];
  arr.push.apply(arr, values);
  arr.__proto__ = MongooseArray.prototype;

  arr._atomics = {};
  arr.validators = [];
  arr._path = path;

  <span class="keyword">if</span> (doc) {
    arr._parent = doc;
    arr._schema = doc.schema.path(path);
  }

  <span class="keyword">return</span> arr;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>values</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array">Array</a>&gt; </span><span></span></li><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>doc</code><span class="types"> &lt;<a href="#document_Document">Document</a>&gt; </span><span>parent document</span></li></ul></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array">Array</a></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://bit.ly/f6CnZU">http://bit.ly/f6CnZU</a></li></ul></div><div class="description"><h4>NOTE:</h4>

<p><em>Values always have to be passed to the constructor to initialize, otherwise <code>MongooseArray#push</code> will mark the array as modified.</em></p></div><hr class="private"></div><div class="item method private"><h3 id="types_array_MongooseArray-_cast"><a href="#types_array_MongooseArray-_cast">MongooseArray#_cast(<code>value</code>)</a></h3><p>Casts a member based on this arrays schema.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseArray.prototype._cast = <span class="function"><span class="keyword">function</span> <span class="params">(value)</span> {</span>
  <span class="keyword">var</span> cast = <span class="keyword">this</span>._schema.caster.cast
    , doc = <span class="keyword">this</span>._parent;

  <span class="keyword">return</span> cast.call(<span class="literal">null</span>, value, doc);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>value</code><span class="types"> &lt;<a href="#any">any</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#value">value</a>&gt; </span><span>the casted value</span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="types_array_MongooseArray-_markModified"><a href="#types_array_MongooseArray-_markModified">MongooseArray#_markModified(<code>embeddedDoc</code>, <code>embeddedPath</code>)</a></h3><p>Marks this array as modified.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseArray.prototype._markModified = <span class="function"><span class="keyword">function</span> <span class="params">(embeddedDoc, embeddedPath)</span> {</span>
  <span class="keyword">var</span> parent = <span class="keyword">this</span>._parent
    , dirtyPath;

  <span class="keyword">if</span> (parent) {
    <span class="keyword">if</span> (arguments.length) {
      <span class="comment">// If an embedded doc bubbled up the change</span>
      dirtyPath = [<span class="keyword">this</span>._path, <span class="keyword">this</span>.indexOf(embeddedDoc), embeddedPath].join(<span class="string">'.'</span>);
    } <span class="keyword">else</span> {
      dirtyPath = <span class="keyword">this</span>._path;
    }
    parent.markModified(dirtyPath);
  }

  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>embeddedDoc</code><span class="types"> &lt;<a href="#types_embedded_EmbeddedDocument">EmbeddedDocument</a>&gt; </span><span>the embedded doc that invoked this method on the Array</span></li><li><code>embeddedPath</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>the path which changed in the embeddedDoc</span></li></ul></div><div class="description"><p>If it bubbles up from an embedded document change, then it takes the following arguments (otherwise, takes 0 arguments)</p></div><hr class="private"></div><div class="item method private"><h3 id="types_array_MongooseArray-_registerAtomic"><a href="#types_array_MongooseArray-_registerAtomic">MongooseArray#_registerAtomic(<code>op</code>, <code>val</code>)</a></h3><p>Register an atomic operation with the parent.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseArray.prototype._registerAtomic = <span class="function"><span class="keyword">function</span> <span class="params">(op, val)</span> {</span>
  <span class="keyword">if</span> (<span class="string">'$set'</span> == op) {
    <span class="comment">// $set takes precedence over all other ops.</span>
    <span class="comment">// mark entire array modified.</span>
    <span class="keyword">this</span>._atomics = { $set: val };
    <span class="keyword">this</span>._markModified();
    <span class="keyword">return</span> <span class="keyword">this</span>;
  }

  <span class="keyword">var</span> atomics = <span class="keyword">this</span>._atomics;

  <span class="comment">// reset pop/shift after save</span>
  <span class="keyword">if</span> (<span class="string">'$pop'</span> == op &amp;&amp; !(<span class="string">'$pop'</span> <span class="keyword">in</span> atomics)) {
    <span class="keyword">var</span> self = <span class="keyword">this</span>;
    <span class="keyword">this</span>._parent.once(<span class="string">'save'</span>, <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
      self._popped = self._shifted = <span class="literal">null</span>;
    });
  }

  <span class="keyword">if</span> (<span class="keyword">this</span>._atomics.$set) {
    <span class="keyword">return</span> <span class="keyword">this</span>;
  }

  <span class="comment">// check for impossible $atomic combos (Mongo denies more than one</span>
  <span class="comment">// $atomic op on a single path</span>
  <span class="keyword">if</span> (Object.keys(atomics).length &amp;&amp; !(op <span class="keyword">in</span> atomics)) {
    <span class="comment">// a different op was previously registered.</span>
    <span class="comment">// save the entire thing.</span>
    <span class="keyword">this</span>._atomics = { $set: <span class="keyword">this</span> };
    <span class="keyword">this</span>._markModified();
    <span class="keyword">return</span> <span class="keyword">this</span>;
  }

  <span class="keyword">if</span> (op === <span class="string">'$pullAll'</span> || op === <span class="string">'$pushAll'</span> || op === <span class="string">'$addToSet'</span>) {
    atomics[op] || (atomics[op] = []);
    atomics[op] = atomics[op].concat(val);
  } <span class="keyword">else</span> <span class="keyword">if</span> (op === <span class="string">'$pullDocs'</span>) {
    <span class="keyword">var</span> pullOp = atomics[<span class="string">'$pull'</span>] || (atomics[<span class="string">'$pull'</span>] = {})
      , selector = pullOp[<span class="string">'_id'</span>] || (pullOp[<span class="string">'_id'</span>] = {<span class="string">'$in'</span> : [] });
    selector[<span class="string">'$in'</span>] = selector[<span class="string">'$in'</span>].concat(val);
  } <span class="keyword">else</span> {
    atomics[op] = val;
  }

  <span class="keyword">this</span>._markModified();
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>op</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array">Array</a>&gt; </span><span>operation</span></li><li><code>val</code><span class="types"> &lt;<a href="#any">any</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="types_array_MongooseArray-hasAtomics"><a href="#types_array_MongooseArray-hasAtomics">MongooseArray#hasAtomics()</a></h3><p>Returns the number of pending atomic operations to send to the db for this array.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseArray.prototype.hasAtomics = <span class="function"><span class="keyword">function</span> <span class="title">hasAtomics</span> <span class="params">()</span> {</span>
  <span class="keyword">if</span> (!(<span class="keyword">this</span>._atomics &amp;&amp; <span class="string">'Object'</span> === <span class="keyword">this</span>._atomics.constructor.name)) {
    <span class="keyword">return</span> <span class="number">0</span>;
  }

  <span class="keyword">return</span> Object.keys(<span class="keyword">this</span>._atomics).length;
}</code></pre></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="types_array_MongooseArray-push"><a href="#types_array_MongooseArray-push">MongooseArray#push(<code>[args...]</code>)</a></h3><p>Wraps <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push"><code>Array#push</code></a> with proper change tracking.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseArray.prototype.push = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">var</span> values = [].map.call(arguments, <span class="keyword">this</span>._cast, <span class="keyword">this</span>)
    , ret = [].push.apply(<span class="keyword">this</span>, values);

  <span class="comment">// $pushAll might be fibbed (could be $push). But it makes it easier to</span>
  <span class="comment">// handle what could have been $push, $pushAll combos</span>
  <span class="keyword">this</span>._registerAtomic(<span class="string">'$pushAll'</span>, values);
  <span class="keyword">return</span> ret;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>[args...]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="types_array_MongooseArray-nonAtomicPush"><a href="#types_array_MongooseArray-nonAtomicPush">MongooseArray#nonAtomicPush(<code>[args...]</code>)</a></h3><p>Pushes items to the array non-atomically.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseArray.prototype.nonAtomicPush = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">var</span> values = [].map.call(arguments, <span class="keyword">this</span>._cast, <span class="keyword">this</span>)
    , ret = [].push.apply(<span class="keyword">this</span>, values);
  <span class="keyword">this</span>._registerAtomic(<span class="string">'$set'</span>, <span class="keyword">this</span>);
  <span class="keyword">return</span> ret;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>[args...]</code><span class="types"> &lt;<a href="#any">any</a>&gt; </span><span></span></li></ul></div><div class="description"><h4>NOTE:</h4>

<p><em>marks the entire array as modified, which if saved, will store it as a <code>$set</code> operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it.</em></p></div><hr class=""></div><div class="item method public"><h3 id="types_array_MongooseArray-%24pop"><a href="#types_array_MongooseArray-%24pop">MongooseArray#$pop()</a></h3><p>Pops the array atomically at most one time per document <code>save()</code>.</p><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop" title="mongodb">mongodb</a></li></ul></div><div class="description"><h4>NOTE:</h4>

<p><em>Calling this mulitple times on an array before saving sends the same command as calling it once.</em><br /><em>This update is implemented using the MongoDB <a href="http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop">$pop</a> method which enforces this restriction.</em></p>

<pre><code>doc.array = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>];

 <span class="keyword">var</span> popped = doc.array.$pop();
 console.log(popped); <span class="comment">// 3</span>
 console.log(doc.array); <span class="comment">// [1,2]</span>

 <span class="comment">// no affect</span>
 popped = doc.array.$pop();
 console.log(doc.array); <span class="comment">// [1,2]</span>

 doc.save(<span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
   <span class="keyword">if</span> (err) <span class="keyword">return</span> handleError(err);

   <span class="comment">// we saved, now $pop works again</span>
   popped = doc.array.$pop();
   console.log(popped); <span class="comment">// 2</span>
   console.log(doc.array); <span class="comment">// [1]</span>
 })</code></pre></div><hr class=""></div><div class="item method public"><h3 id="types_array_MongooseArray-pop"><a href="#types_array_MongooseArray-pop">MongooseArray#pop()</a></h3><p>Wraps <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/pop"><code>Array#pop</code></a> with proper change tracking.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseArray.prototype.pop = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">var</span> ret = [].pop.call(<span class="keyword">this</span>);
  <span class="keyword">this</span>._registerAtomic(<span class="string">'$set'</span>, <span class="keyword">this</span>);
  <span class="keyword">return</span> ret;
};</code></pre></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="#types_array_MongooseArray-%24pop" title="MongooseArray#$pop">MongooseArray#$pop</a></li></ul></div><div class="description"><h4>Note:</h4>

<p><em>marks the entire array as modified which will pass the entire thing to $set potentially overwritting any changes that happen between when you retrieved the object and when you save it.</em></p></div><hr class=""></div><div class="item method public"><h3 id="types_array_MongooseArray-%24shift"><a href="#types_array_MongooseArray-%24shift">MongooseArray#$shift()</a></h3><p>Atomically shifts the array at most one time per document <code>save()</code>.</p><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop" title="mongodb">mongodb</a></li></ul></div><div class="description"><h4>NOTE:</h4>

<p><em>Calling this mulitple times on an array before saving sends the same command as calling it once.</em><br /><em>This update is implemented using the MongoDB <a href="http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pop">$pop</a> method which enforces this restriction.</em></p>

<pre><code>doc.array = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>];

 <span class="keyword">var</span> shifted = doc.array.$shift();
 console.log(shifted); <span class="comment">// 1</span>
 console.log(doc.array); <span class="comment">// [2,3]</span>

 <span class="comment">// no affect</span>
 shifted = doc.array.$shift();
 console.log(doc.array); <span class="comment">// [2,3]</span>

 doc.save(<span class="function"><span class="keyword">function</span> <span class="params">(err)</span> {</span>
   <span class="keyword">if</span> (err) <span class="keyword">return</span> handleError(err);

   <span class="comment">// we saved, now $shift works again</span>
   shifted = doc.array.$shift();
   console.log(shifted ); <span class="comment">// 2</span>
   console.log(doc.array); <span class="comment">// [3]</span>
 })</code></pre></div><hr class=""></div><div class="item method public"><h3 id="types_array_MongooseArray-shift"><a href="#types_array_MongooseArray-shift">MongooseArray#shift()</a></h3><p>Wraps <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift"><code>Array#shift</code></a> with proper change tracking.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseArray.prototype.shift = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">var</span> ret = [].shift.call(<span class="keyword">this</span>);
  <span class="keyword">this</span>._registerAtomic(<span class="string">'$set'</span>, <span class="keyword">this</span>);
  <span class="keyword">return</span> ret;
};</code></pre></div><div class="description"><h4>Example:</h4>

<pre><code>doc.array = [<span class="number">2</span>,<span class="number">3</span>];
<span class="keyword">var</span> res = doc.array.shift();
console.log(res) <span class="comment">// 2</span>
console.log(doc.array) <span class="comment">// [3]</span></code></pre>

<h4>Note:</h4>

<p><em>marks the entire array as modified, which if saved, will store it as a <code>$set</code> operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it.</em></p></div><hr class=""></div><div class="item method public"><h3 id="types_array_MongooseArray-remove"><a href="#types_array_MongooseArray-remove">MongooseArray#remove(<code>[args...]</code>)</a></h3><p>Removes items from an array atomically</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseArray.prototype.remove = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">var</span> args = [].map.call(arguments, <span class="keyword">this</span>._cast, <span class="keyword">this</span>);
  <span class="keyword">if</span> (args.length == <span class="number">1</span>)
    <span class="keyword">this</span>.pull(args[<span class="number">0</span>]);
  <span class="keyword">else</span>
    <span class="keyword">this</span>.pull.apply(<span class="keyword">this</span>, args);
  <span class="keyword">return</span> args;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>[args...]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>values to remove</span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull" title="mongodb">mongodb</a></li></ul></div><div class="description"><h4>Examples:</h4>

<pre><code>doc.array.remove(ObjectId)
doc.array.remove(<span class="string">'tag 1'</span>, <span class="string">'tag 2'</span>)</code></pre></div><hr class=""></div><div class="item method public"><h3 id="types_array_MongooseArray-pull"><a href="#types_array_MongooseArray-pull">MongooseArray#pull(<code>[args...]</code>)</a></h3><p>Pulls items from the array atomically.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseArray.prototype.pull = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">var</span> values = [].map.call(arguments, <span class="keyword">this</span>._cast, <span class="keyword">this</span>)
    , cur = <span class="keyword">this</span>._parent.get(<span class="keyword">this</span>._path)
    , i = cur.length
    , mem;

  <span class="keyword">while</span> (i--) {
    mem = cur[i];
    <span class="keyword">if</span> (mem <span class="keyword">instanceof</span> EmbeddedDocument) {
      <span class="keyword">if</span> (values.some(<span class="function"><span class="keyword">function</span> <span class="params">(v)</span> {</span> <span class="keyword">return</span> v.equals(mem); } )) {
        [].splice.call(cur, i, <span class="number">1</span>);
      }
    } <span class="keyword">else</span> <span class="keyword">if</span> (~cur.indexOf.call(values, mem)) {
      [].splice.call(cur, i, <span class="number">1</span>);
    }
  }

  <span class="keyword">if</span> (values[<span class="number">0</span>] <span class="keyword">instanceof</span> EmbeddedDocument) {
    <span class="keyword">this</span>._registerAtomic(<span class="string">'$pullDocs'</span>, values.map( <span class="function"><span class="keyword">function</span> <span class="params">(v)</span> {</span> <span class="keyword">return</span> v._id; } ));
  } <span class="keyword">else</span> {
    <span class="keyword">this</span>._registerAtomic(<span class="string">'$pullAll'</span>, values);
  }

  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>[args...]</code><span class="types"> &lt;<a href="#any">any</a>&gt; </span><span></span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://www.mongodb.org/display/DOCS/Updating/#Updating-%24pull" title="mongodb">mongodb</a></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="types_array_MongooseArray-splice"><a href="#types_array_MongooseArray-splice">MongooseArray#splice()</a></h3><p>Wraps <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/splice"><code>Array#splice</code></a> with proper change tracking.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseArray.prototype.splice = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">if</span> (arguments.length) {
    <span class="keyword">var</span> ret = [].splice.apply(<span class="keyword">this</span>, arguments);
    <span class="keyword">this</span>._registerAtomic(<span class="string">'$set'</span>, <span class="keyword">this</span>);
  }
  <span class="keyword">return</span> ret;
};</code></pre></div><div class="description"><h4>Note:</h4>

<p><em>marks the entire array as modified, which if saved, will store it as a <code>$set</code> operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it.</em></p></div><hr class=""></div><div class="item method public"><h3 id="types_array_MongooseArray-unshift"><a href="#types_array_MongooseArray-unshift">MongooseArray#unshift()</a></h3><p>Wraps <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/unshift"><code>Array#unshift</code></a> with proper change tracking.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseArray.prototype.unshift = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">var</span> values = [].map.call(arguments, <span class="keyword">this</span>._cast, <span class="keyword">this</span>);
  [].unshift.apply(<span class="keyword">this</span>, values);
  <span class="keyword">this</span>._registerAtomic(<span class="string">'$set'</span>, <span class="keyword">this</span>);
  <span class="keyword">return</span> <span class="keyword">this</span>.length;
};</code></pre></div><div class="description"><h4>Note:</h4>

<p><em>marks the entire array as modified, which if saved, will store it as a <code>$set</code> operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it.</em></p></div><hr class=""></div><div class="item method public"><h3 id="types_array_MongooseArray-sort"><a href="#types_array_MongooseArray-sort">MongooseArray#sort()</a></h3><p>Wraps <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/sort"><code>Array#sort</code></a> with proper change tracking.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseArray.prototype.sort = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">var</span> ret = [].sort.apply(<span class="keyword">this</span>, arguments);
  <span class="keyword">this</span>._registerAtomic(<span class="string">'$set'</span>, <span class="keyword">this</span>);
  <span class="keyword">return</span> ret;
}</code></pre></div><div class="description"><h4>NOTE:</h4>

<p><em>marks the entire array as modified, which if saved, will store it as a <code>$set</code> operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it.</em></p></div><hr class=""></div><div class="item method public"><h3 id="types_array_MongooseArray-addToSet"><a href="#types_array_MongooseArray-addToSet">MongooseArray#addToSet(<code>[args...]</code>)</a></h3><p>Adds values to the array if not already present.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseArray.prototype.addToSet = <span class="function"><span class="keyword">function</span> <span class="title">addToSet</span> <span class="params">()</span> {</span>
  <span class="keyword">var</span> values = [].map.call(arguments, <span class="keyword">this</span>._cast, <span class="keyword">this</span>)
    , added = []
    , type = values[<span class="number">0</span>] <span class="keyword">instanceof</span> EmbeddedDocument ? <span class="string">'doc'</span> :
             values[<span class="number">0</span>] <span class="keyword">instanceof</span> Date ? <span class="string">'date'</span> :
             <span class="string">''</span>;

  values.forEach(<span class="function"><span class="keyword">function</span> <span class="params">(v)</span> {</span>
    <span class="keyword">var</span> found;
    <span class="keyword">switch</span> (type) {
      <span class="keyword">case</span> <span class="string">'doc'</span>:
        found = <span class="keyword">this</span>.some(<span class="keyword">function</span>(doc){ <span class="keyword">return</span> doc.equals(v) });
        <span class="keyword">break</span>;
      <span class="keyword">case</span> <span class="string">'date'</span>:
        <span class="keyword">var</span> val = +v;
        found = <span class="keyword">this</span>.some(<span class="keyword">function</span>(d){ <span class="keyword">return</span> +d === val });
        <span class="keyword">break</span>;
      <span class="keyword">default</span>:
        found = ~<span class="keyword">this</span>.indexOf(v);
    }

    <span class="keyword">if</span> (!found) {
      [].push.call(<span class="keyword">this</span>, v);
      <span class="keyword">this</span>._registerAtomic(<span class="string">'$addToSet'</span>, v);
      [].push.call(added, v);
    }
  }, <span class="keyword">this</span>);

  <span class="keyword">return</span> added;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>[args...]</code><span class="types"> &lt;<a href="#any">any</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array">Array</a>&gt; </span><span>the values that were added</span></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code>console.log(doc.array) <span class="comment">// [2,3,4]</span>
<span class="keyword">var</span> added = doc.array.addToSet(<span class="number">4</span>,<span class="number">5</span>);
console.log(doc.array) <span class="comment">// [2,3,4,5]</span>
console.log(added)     <span class="comment">// [5]</span></code></pre></div><hr class=""></div><div class="item method public"><h3 id="types_array_MongooseArray-toObject"><a href="#types_array_MongooseArray-toObject">MongooseArray#toObject(<code>options</code>)</a></h3><p>Returns a native js Array.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseArray.prototype.toObject = <span class="function"><span class="keyword">function</span> <span class="params">(options)</span> {</span>
  <span class="keyword">if</span> (options &amp;&amp; options.depopulate &amp;&amp; <span class="keyword">this</span>[<span class="number">0</span>] <span class="keyword">instanceof</span> Document) {
    <span class="keyword">return</span> <span class="keyword">this</span>.map(<span class="function"><span class="keyword">function</span> <span class="params">(doc)</span> {</span>
      <span class="keyword">return</span> doc._id;
    });
  }

  <span class="comment">// return this.slice()?</span>
  <span class="keyword">return</span> <span class="keyword">this</span>.map(<span class="function"><span class="keyword">function</span> <span class="params">(doc)</span> {</span>
    <span class="keyword">return</span> doc;
  });
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>options</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array">Array</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="types_array_MongooseArray-inspect"><a href="#types_array_MongooseArray-inspect">MongooseArray#inspect()</a></h3><p>Helper for console.log</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseArray.prototype.inspect = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">return</span> <span class="string">'['</span> + <span class="keyword">this</span>.map(<span class="function"><span class="keyword">function</span> <span class="params">(doc)</span> {</span>
    <span class="keyword">return</span> <span class="string">' '</span> + doc;
  }) + <span class="string">' ]'</span>;
};</code></pre></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="types_array_MongooseArray-indexOf"><a href="#types_array_MongooseArray-indexOf">MongooseArray#indexOf(<code>obj</code>)</a></h3><p>Return the index of <code>obj</code> or <code>-1</code> if not found.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseArray.prototype.indexOf = <span class="function"><span class="keyword">function</span> <span class="title">indexOf</span> <span class="params">(obj)</span> {</span>
  <span class="keyword">if</span> (obj <span class="keyword">instanceof</span> ObjectId) obj = obj.toString();
  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>, len = <span class="keyword">this</span>.length; i &lt; len; ++i) {
    <span class="keyword">if</span> (obj == <span class="keyword">this</span>[i])
      <span class="keyword">return</span> i;
  }
  <span class="keyword">return</span> -<span class="number">1</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>obj</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>the item to look for</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class=""></div><div class="item property private"><h3 id="types_array_MongooseArray-_parent"><a href="#types_array_MongooseArray-_parent">MongooseArray#<span>_parent</span></a></h3><p>Parent owner document</p><hr class="private"></div><div class="item property private"><h3 id="types_array_MongooseArray-_atomics"><a href="#types_array_MongooseArray-_atomics">MongooseArray#<span>_atomics</span></a></h3><p>Stores a queue of atomic operations to perform</p><hr class="private"></div></li><li class="module "><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/types/buffer.js" id="types-buffer-js">types/buffer.js</a><div class="item method private"><h3 id="types_buffer_MongooseBuffer"><a href="#types_buffer_MongooseBuffer">MongooseBuffer(<code>value</code>, <code>encode</code>, <code>offset</code>)</a></h3><p>Mongoose Buffer constructor.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">MongooseBuffer</span> <span class="params">(value, encode, offset)</span> {</span>
  <span class="keyword">var</span> length = arguments.length;
  <span class="keyword">var</span> val;

  <span class="keyword">if</span> (<span class="number">0</span> === length || <span class="literal">null</span> === arguments[<span class="number">0</span>] || <span class="literal">undefined</span> === arguments[<span class="number">0</span>]) {
    val = <span class="number">0</span>;
  } <span class="keyword">else</span> {
    val = value;
  }

  <span class="keyword">var</span> encoding;
  <span class="keyword">var</span> path;
  <span class="keyword">var</span> doc;

  <span class="keyword">if</span> (Array.isArray(encode)) {
    <span class="comment">// internal casting</span>
    path = encode[<span class="number">0</span>];
    doc = encode[<span class="number">1</span>];
  } <span class="keyword">else</span> {
    encoding = encode;
  }

  <span class="keyword">var</span> buf = <span class="keyword">new</span> Buffer(val, encoding, offset);
  buf.__proto__ = MongooseBuffer.prototype;

  <span class="comment">// make sure these internal props don't show up in Object.keys()</span>
  Object.defineProperties(buf, {
      validators: { value: [] }
    , _path: { value: path }
    , _parent: { value: doc }
  });

  <span class="keyword">if</span> (doc &amp;&amp; <span class="string">"string"</span> === <span class="keyword">typeof</span> path) {
    Object.defineProperty(buf, <span class="string">'_schema'</span>, {
        value: doc.schema.path(path)
    });
  }

  <span class="keyword">return</span> buf;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>value</code><span class="types"> &lt;<a href="http://nodejs.org/api/buffer.html">Buffer</a>&gt; </span><span></span></li><li><code>encode</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li><li><code>offset</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>&gt; </span><span></span></li></ul></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="http://nodejs.org/api/buffer.html">Buffer</a></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://bit.ly/f6CnZU">http://bit.ly/f6CnZU</a></li></ul></div><div class="description"><p>Values always have to be passed to the constructor to initialize.</p></div><hr class="private"></div><div class="item method private"><h3 id="types_buffer_MongooseBuffer-_markModified"><a href="#types_buffer_MongooseBuffer-_markModified">MongooseBuffer#_markModified()</a></h3><p>Marks this buffer as modified.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseBuffer.prototype._markModified = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">var</span> parent = <span class="keyword">this</span>._parent;

  <span class="keyword">if</span> (parent) {
    parent.markModified(<span class="keyword">this</span>._path);
  }
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="types_buffer_MongooseBuffer-write"><a href="#types_buffer_MongooseBuffer-write">MongooseBuffer#write()</a></h3><p>Writes the buffer.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseBuffer.prototype.write = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">var</span> written = Buffer.prototype.write.apply(<span class="keyword">this</span>, arguments);

  <span class="keyword">if</span> (written > <span class="number">0</span>) {
    <span class="keyword">this</span>._markModified();
  }

  <span class="keyword">return</span> written;
};</code></pre></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="types_buffer_MongooseBuffer-copy"><a href="#types_buffer_MongooseBuffer-copy">MongooseBuffer#copy(<code>target</code>)</a></h3><p>Copies the buffer.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseBuffer.prototype.copy = <span class="function"><span class="keyword">function</span> <span class="params">(target)</span> {</span>
  <span class="keyword">var</span> ret = Buffer.prototype.copy.apply(<span class="keyword">this</span>, arguments);

  <span class="keyword">if</span> (target <span class="keyword">instanceof</span> MongooseBuffer) {
    target._markModified();
  }

  <span class="keyword">return</span> ret;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>target</code><span class="types"> &lt;<a href="http://nodejs.org/api/buffer.html">Buffer</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#types_buffer_MongooseBuffer">MongooseBuffer</a>&gt; </span><span></span></li></ul></div><div class="description"><h4>Note:</h4>

<p><code>Buffer#copy</code> does not mark <code>target</code> as modified so you must copy from a <code>MongooseBuffer</code> for it to work as expected. This is a work around since <code>copy</code> modifies the target, not this.</p></div><hr class=""></div><div class="item method public"><h3 id="types_buffer_MongooseBuffer-toObject"><a href="#types_buffer_MongooseBuffer-toObject">MongooseBuffer#toObject(<code>[subtype]</code>)</a></h3><p>Converts this buffer to its Binary type representation.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseBuffer.prototype.toObject = <span class="function"><span class="keyword">function</span> <span class="params">(subtype)</span> {</span>
  subtype = <span class="keyword">typeof</span> subtype !== <span class="string">'undefined'</span> ? subtype : <span class="number">0x00</span>
  <span class="keyword">return</span> <span class="keyword">new</span> Binary(<span class="keyword">this</span>, subtype);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>[subtype]</code><span class="types"> &lt;<a href="#Hex">Hex</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://github.com/mongodb/js-bson/blob/master/lib/bson/binary.js">Binary</a>&gt; </span><span></span></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://bsonspec.org/#/specification">http://bsonspec.org/#/specification</a></li></ul></div><div class="description"><h4>SubTypes:</h4>

<ul>
<li>0x00: Binary/Generic</li>
<li>0x01: Function</li>
<li>0x02: Binary (Deprecated, 0x00 is new default)</li>
<li>0x03: UUID</li>
<li>0x04: MD5</li>
<li>0x80: User Defined</li>
</ul></div><hr class=""></div><div class="item property private"><h3 id="types_buffer_MongooseBuffer-_parent"><a href="#types_buffer_MongooseBuffer-_parent">MongooseBuffer#<span>_parent</span></a></h3><p>Parent owner document</p><hr class="private"></div></li><li class="module "><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/types/documentarray.js" id="types-documentarray-js">types/documentarray.js</a><div class="item method private"><h3 id="types_documentarray_MongooseDocumentArray"><a href="#types_documentarray_MongooseDocumentArray">MongooseDocumentArray(<code>values</code>, <code>path</code>, <code>doc</code>)</a></h3><p>DocumentArray constructor</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">MongooseDocumentArray</span> <span class="params">(values, path, doc)</span> {</span>
  <span class="keyword">var</span> arr = [];

  <span class="comment">// Values always have to be passed to the constructor to initialize, since</span>
  <span class="comment">// otherwise MongooseArray#push will mark the array as modified to the parent.</span>
  arr.push.apply(arr, values);
  arr.__proto__ = MongooseDocumentArray.prototype;

  arr._atomics = {};
  arr.validators = [];
  arr._path = path;

  <span class="keyword">if</span> (doc) {
    arr._parent = doc;
    arr._schema = doc.schema.path(path);
    doc.on(<span class="string">'save'</span>, arr.notify(<span class="string">'save'</span>));
    doc.on(<span class="string">'isNew'</span>, arr.notify(<span class="string">'isNew'</span>));
  }

  <span class="keyword">return</span> arr;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>values</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array">Array</a>&gt; </span><span></span></li><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>the path to this array</span></li><li><code>doc</code><span class="types"> &lt;<a href="#document_Document">Document</a>&gt; </span><span>parent document</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#types_documentarray_MongooseDocumentArray">MongooseDocumentArray</a>&gt; </span><span></span></li></ul></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="#types_array_MongooseArray">MongooseArray</a></li></ul></div><div class="see"><h4>See:</h4><ul class="see"><li><a href="http://bit.ly/f6CnZU">http://bit.ly/f6CnZU</a></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method private"><h3 id="types_documentarray_MongooseDocumentArray-_cast"><a href="#types_documentarray_MongooseDocumentArray-_cast">MongooseDocumentArray#_cast()</a></h3><p>Overrides MongooseArray#cast</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseDocumentArray.prototype._cast = <span class="function"><span class="keyword">function</span> <span class="params">(value)</span> {</span>
  <span class="keyword">var</span> doc = <span class="keyword">new</span> <span class="keyword">this</span>._schema.casterConstructor(value, <span class="keyword">this</span>);
  <span class="keyword">return</span> doc;
};</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="types_documentarray_MongooseDocumentArray-id"><a href="#types_documentarray_MongooseDocumentArray-id">MongooseDocumentArray#id(<code>id</code>)</a></h3><p>Searches array items for the first document with a matching id.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseDocumentArray.prototype.id = <span class="function"><span class="keyword">function</span> <span class="params">(id)</span> {</span>
  <span class="keyword">var</span> casted
    , _id;

  <span class="keyword">try</span> {
    casted = ObjectId.toString(ObjectIdSchema.prototype.cast.call({}, id));
  } <span class="keyword">catch</span> (e) {
    casted = <span class="literal">null</span>;
  }

  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>, l = <span class="keyword">this</span>.length; i &lt; l; i++) {
    _id = <span class="keyword">this</span>[i].get(<span class="string">'_id'</span>);
    <span class="keyword">if</span> (!(_id <span class="keyword">instanceof</span> ObjectId)) {
      <span class="keyword">if</span> (String(id) == _id)
        <span class="keyword">return</span> <span class="keyword">this</span>[i];
    } <span class="keyword">else</span> {
      <span class="keyword">if</span> (casted == _id)
        <span class="keyword">return</span> <span class="keyword">this</span>[i];
    }
  }

  <span class="keyword">return</span> <span class="literal">null</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>id</code><span class="types"> &lt;<a href="#types_objectid_ObjectId">ObjectId</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Number">Number</a>, <a href="http://nodejs.org/api/buffer.html">Buffer</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#types_embedded_EmbeddedDocument">EmbeddedDocument</a>, <a href="#null">null</a>&gt; </span><span>the subdocuent or null if not found.</span></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code><span class="keyword">var</span> embeddedDoc = m.array.id(some_id);</code></pre></div><hr class=""></div><div class="item method public"><h3 id="types_documentarray_MongooseDocumentArray-toObject"><a href="#types_documentarray_MongooseDocumentArray-toObject">MongooseDocumentArray#toObject()</a></h3><p>Returns a native js Array of plain js objects</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseDocumentArray.prototype.toObject = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">return</span> <span class="keyword">this</span>.map(<span class="function"><span class="keyword">function</span> <span class="params">(doc)</span> {</span>
    <span class="keyword">return</span> doc &amp;&amp; doc.toObject() || <span class="literal">null</span>;
  });
};</code></pre></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array">Array</a>&gt; </span><span></span></li></ul></div><div class="description"><h4>NOTE:</h4>

<p><em>Each sub-document is converted to a plain object by calling its <code>#toObject</code> method.</em></p></div><hr class=""></div><div class="item method public"><h3 id="types_documentarray_MongooseDocumentArray-inspect"><a href="#types_documentarray_MongooseDocumentArray-inspect">MongooseDocumentArray#inspect()</a></h3><p>Helper for console.log</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseDocumentArray.prototype.inspect = function () {
  return '[' + this.map(function (doc) {
    if (doc) {
      return doc.inspect
        ? doc.inspect()
        : util.inspect(doc)
    }
    return 'null'
  }).join('
') + ']';
};</code></pre></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="types_documentarray_MongooseDocumentArray-create"><a href="#types_documentarray_MongooseDocumentArray-create">MongooseDocumentArray#create(<code>obj</code>)</a></h3><p>Creates a subdocument casted to this schema.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseDocumentArray.prototype.create = <span class="function"><span class="keyword">function</span> <span class="params">(obj)</span> {</span>
  <span class="keyword">return</span> <span class="keyword">new</span> <span class="keyword">this</span>._schema.casterConstructor(obj);
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>obj</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>the value to cast to this arrays SubDocument schema</span></li></ul></div><div class="description"><p>This is the same subdocument constructor used for casting.</p></div><hr class=""></div><div class="item method private"><h3 id="types_documentarray_MongooseDocumentArray-notify"><a href="#types_documentarray_MongooseDocumentArray-notify">MongooseDocumentArray#notify(<code>event</code>)</a></h3><p>Creates a fn that notifies all child docs of <code>event</code>.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">MongooseDocumentArray.prototype.notify = <span class="function"><span class="keyword">function</span> <span class="title">notify</span> <span class="params">(event)</span> {</span>
  <span class="keyword">var</span> self = <span class="keyword">this</span>;
  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="title">notify</span> <span class="params">(val)</span> {</span>
    <span class="keyword">var</span> i = self.length;
    <span class="keyword">while</span> (i--) {
      self[i].emit(event, val);
    }
  }
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>event</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class="private"></div></li><li class="module "><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/types/embedded.js" id="types-embedded-js">types/embedded.js</a><div class="item method private"><h3 id="types_embedded_EmbeddedDocument"><a href="#types_embedded_EmbeddedDocument">EmbeddedDocument(<code>obj</code>, <code>parentArr</code>, <code>skipId</code>)</a></h3><p>EmbeddedDocument constructor.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">EmbeddedDocument</span> <span class="params">(obj, parentArr, skipId, fields)</span> {</span>
  <span class="keyword">if</span> (parentArr) {
    <span class="keyword">this</span>.__parentArray = parentArr;
    <span class="keyword">this</span>.__parent = parentArr._parent;
  } <span class="keyword">else</span> {
    <span class="keyword">this</span>.__parentArray = <span class="literal">undefined</span>;
    <span class="keyword">this</span>.__parent = <span class="literal">undefined</span>;
  }

  Document.call(<span class="keyword">this</span>, obj, fields, skipId);

  <span class="keyword">var</span> self = <span class="keyword">this</span>;
  <span class="keyword">this</span>.on(<span class="string">'isNew'</span>, <span class="function"><span class="keyword">function</span> <span class="params">(val)</span> {</span>
    self.isNew = val;
  });
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>obj</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>js object returned from the db</span></li><li><code>parentArr</code><span class="types"> &lt;<a href="#types_documentarray_MongooseDocumentArray">MongooseDocumentArray</a>&gt; </span><span>the parent array of this document</span></li><li><code>skipId</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span></span></li></ul></div><div class="inherits"><h4>Inherits:</h4><ul><li><a href="#document_Document">Document</a></li></ul></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="types_embedded_EmbeddedDocument-markModified"><a href="#types_embedded_EmbeddedDocument-markModified">EmbeddedDocument#markModified(<code>path</code>)</a></h3><p>Marks the embedded doc modified.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">EmbeddedDocument.prototype.markModified = <span class="function"><span class="keyword">function</span> <span class="params">(path)</span> {</span>
  <span class="keyword">if</span> (!<span class="keyword">this</span>.__parentArray) <span class="keyword">return</span>;

  <span class="keyword">this</span>._activePaths.modify(path);

  <span class="keyword">if</span> (<span class="keyword">this</span>.isNew) {
    <span class="comment">// Mark the WHOLE parent array as modified</span>
    <span class="comment">// if this is a new document (i.e., we are initializing</span>
    <span class="comment">// a document),</span>
    <span class="keyword">this</span>.__parentArray._markModified();
  } <span class="keyword">else</span>
    <span class="keyword">this</span>.__parentArray._markModified(<span class="keyword">this</span>, path);
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>the path which changed</span></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code><span class="keyword">var</span> doc = blogpost.comments.id(hexstring);
doc.mixed.type = <span class="string">'changed'</span>;
doc.markModified(<span class="string">'mixed.type'</span>);</code></pre></div><hr class=""></div><div class="item method private"><h3 id="types_embedded_EmbeddedDocument-save"><a href="#types_embedded_EmbeddedDocument-save">EmbeddedDocument#save(<code>[fn]</code>)</a></h3><p>Used as a stub for <a href="https://github.com/bnoguchi/hooks-js/tree/31ec571cef0332e21121ee7157e0cf9728572cc3">hooks.js</a></p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">EmbeddedDocument.prototype.save = <span class="keyword">function</span>(fn) {
  <span class="keyword">if</span> (fn)
    fn(<span class="literal">null</span>);
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>[fn]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#types_embedded_EmbeddedDocument">EmbeddedDocument</a>&gt; </span><span>this</span></li></ul></div><div class="description"><h4>NOTE:</h4>

<p><em>This is a no-op. Does not actually save the doc to the db.</em></p></div><hr class="private"></div><div class="item method public"><h3 id="types_embedded_EmbeddedDocument-remove"><a href="#types_embedded_EmbeddedDocument-remove">EmbeddedDocument#remove(<code>[fn]</code>)</a></h3><p>Removes the subdocument from its parent array.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">EmbeddedDocument.prototype.remove = <span class="function"><span class="keyword">function</span> <span class="params">(fn)</span> {</span>
  <span class="keyword">if</span> (!<span class="keyword">this</span>.__parentArray) <span class="keyword">return</span> <span class="keyword">this</span>;

  <span class="keyword">var</span> _id;
  <span class="keyword">if</span> (!<span class="keyword">this</span>.willRemove) {
    _id = <span class="keyword">this</span>._doc._id;
    <span class="keyword">if</span> (!_id) {
      <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">'For your own good, Mongoose does not know '</span> + 
                      <span class="string">'how to remove an EmbeddedDocument that has no _id'</span>);
    }
    <span class="keyword">this</span>.__parentArray.pull({ _id: _id });
    <span class="keyword">this</span>.willRemove = <span class="literal">true</span>;
  }

  <span class="keyword">if</span> (fn)
    fn(<span class="literal">null</span>);

  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>[fn]</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method private"><h3 id="types_embedded_EmbeddedDocument-update"><a href="#types_embedded_EmbeddedDocument-update">EmbeddedDocument#update()</a></h3><p>Override #update method of parent documents.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">EmbeddedDocument.prototype.update = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">throw</span> <span class="keyword">new</span> Error(<span class="string">'The #update method is not available on EmbeddedDocuments'</span>);
}</code></pre></div><div class="description"></div><hr class="private"></div><div class="item method public"><h3 id="types_embedded_EmbeddedDocument-inspect"><a href="#types_embedded_EmbeddedDocument-inspect">EmbeddedDocument#inspect()</a></h3><p>Helper for console.log</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">EmbeddedDocument.prototype.inspect = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">return</span> inspect(<span class="keyword">this</span>.toObject());
};</code></pre></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="types_embedded_EmbeddedDocument-invalidate"><a href="#types_embedded_EmbeddedDocument-invalidate">EmbeddedDocument#invalidate(<code>path</code>, <code>err</code>)</a></h3><p>Marks a path as invalid, causing validation to fail.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">EmbeddedDocument.prototype.invalidate = <span class="function"><span class="keyword">function</span> <span class="params">(path, err, first)</span> {</span>
  <span class="keyword">if</span> (!<span class="keyword">this</span>.__parent) <span class="keyword">return</span> <span class="literal">false</span>;
  <span class="keyword">var</span> index = <span class="keyword">this</span>.__parentArray.indexOf(<span class="keyword">this</span>);
  <span class="keyword">var</span> parentPath = <span class="keyword">this</span>.__parentArray._path;
  <span class="keyword">var</span> fullPath = [parentPath, index, path].join(<span class="string">'.'</span>);
  <span class="keyword">this</span>.__parent.invalidate(fullPath, err);
  <span class="keyword">if</span> (first)
    <span class="keyword">this</span>._validationError = ownerDocument(<span class="keyword">this</span>)._validationError;
  <span class="keyword">return</span> <span class="literal">true</span>;
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>path</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>the field to invalidate</span></li><li><code>err</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>, <a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error">Error</a>&gt; </span><span>error which states the reason `path` was invalid</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="types_embedded_EmbeddedDocument-ownerDocument"><a href="#types_embedded_EmbeddedDocument-ownerDocument">EmbeddedDocument#ownerDocument()</a></h3><p>Returns the top level document of this sub-document.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">EmbeddedDocument.prototype.ownerDocument = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">return</span> ownerDocument(<span class="keyword">this</span>);
}</code></pre></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#document_Document">Document</a>&gt; </span><span></span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="types_embedded_EmbeddedDocument-parent"><a href="#types_embedded_EmbeddedDocument-parent">EmbeddedDocument#parent()</a></h3><p>Returns this sub-documents parent document.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">EmbeddedDocument.prototype.parent = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">return</span> <span class="keyword">this</span>.__parent;
}</code></pre></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="types_embedded_EmbeddedDocument-parentArray"><a href="#types_embedded_EmbeddedDocument-parentArray">EmbeddedDocument#parentArray()</a></h3><p>Returns this sub-documents parent array.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">EmbeddedDocument.prototype.parentArray = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">return</span> <span class="keyword">this</span>.__parentArray;
}</code></pre></div><div class="description"></div><hr class=""></div></li><li class="module "><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/types/objectid.js" id="types-objectid-js">types/objectid.js</a><div class="item method public"><h3 id="types_objectid_ObjectId"><a href="#types_objectid_ObjectId">ObjectId()</a></h3><p>ObjectId type constructor</p><div class="description"><h4>Example</h4>

<pre><code><span class="keyword">var</span> id = <span class="keyword">new</span> mongoose.Types.ObjectId;</code></pre></div><hr class=""></div><div class="item static private"><h3 id="types_objectid_ObjectId-fromString"><a href="#types_objectid_ObjectId-fromString">ObjectId.fromString(<code>str</code>)</a></h3><p>Creates an ObjectId from <code>str</code></p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">ObjectId.fromString;</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>str</code><span class="types"> &lt;<a href="#types_objectid_ObjectId">ObjectId</a>, <a href="#HexString">HexString</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#types_objectid_ObjectId">ObjectId</a>&gt; </span><span></span></li></ul></div><hr class="private"></div><div class="item static private"><h3 id="types_objectid_ObjectId-toString"><a href="#types_objectid_ObjectId-toString">ObjectId.toString(<code>oid</code>)</a></h3><p>Converts <code>oid</code> to a string.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">ObjectId.toString;</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>oid</code><span class="types"> &lt;<a href="#types_objectid_ObjectId">ObjectId</a>&gt; </span><span>ObjectId instance</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span></span></li></ul></div><hr class="private"></div></li><li class="module "><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/utils.js" id="utils-js">utils.js</a><div class="item static private"><h3 id="utils_exports-toCollectionName"><a href="#utils_exports-toCollectionName">exports.toCollectionName(<code>name</code>)</a></h3><p>Produces a collection name from model <code>name</code>.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">exports.toCollectionName = <span class="function"><span class="keyword">function</span> <span class="params">(name)</span> {</span>
  <span class="keyword">if</span> (<span class="string">'system.profile'</span> === name) <span class="keyword">return</span> name;
  <span class="keyword">if</span> (<span class="string">'system.indexes'</span> === name) <span class="keyword">return</span> name;
  <span class="keyword">return</span> pluralize(name.toLowerCase());
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>name</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>a model name</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String">String</a>&gt; </span><span>a collection name</span></li></ul></div><hr class="private"></div><div class="item static public"><h3 id="utils_exports-pluralization"><a href="#utils_exports-pluralization">exports.pluralization</a></h3><p>Pluralization rules.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">exports.pluralization = [
  [<span class="regexp">/(m)an$/gi</span>, <span class="string">'$1en'</span>],
  [<span class="regexp">/(pe)rson$/gi</span>, <span class="string">'$1ople'</span>],
  [<span class="regexp">/(child)$/gi</span>, <span class="string">'$1ren'</span>],
  [<span class="regexp">/^(ox)$/gi</span>, <span class="string">'$1en'</span>],
  [<span class="regexp">/(ax|test)is$/gi</span>, <span class="string">'$1es'</span>],
  [<span class="regexp">/(octop|vir)us$/gi</span>, <span class="string">'$1i'</span>],
  [<span class="regexp">/(alias|status)$/gi</span>, <span class="string">'$1es'</span>],
  [<span class="regexp">/(bu)s$/gi</span>, <span class="string">'$1ses'</span>],
  [<span class="regexp">/(buffal|tomat|potat)o$/gi</span>, <span class="string">'$1oes'</span>],
  [<span class="regexp">/([ti])um$/gi</span>, <span class="string">'$1a'</span>],
  [<span class="regexp">/sis$/gi</span>, <span class="string">'ses'</span>],
  [<span class="regexp">/(?:([^f])fe|([lr])f)$/gi</span>, <span class="string">'$1$2ves'</span>],
  [<span class="regexp">/(hive)$/gi</span>, <span class="string">'$1s'</span>],
  [<span class="regexp">/([^aeiouy]|qu)y$/gi</span>, <span class="string">'$1ies'</span>],
  [<span class="regexp">/(x|ch|ss|sh)$/gi</span>, <span class="string">'$1es'</span>],
  [<span class="regexp">/(matr|vert|ind)ix|ex$/gi</span>, <span class="string">'$1ices'</span>],
  [<span class="regexp">/([m|l])ouse$/gi</span>, <span class="string">'$1ice'</span>],
  [<span class="regexp">/(quiz)$/gi</span>, <span class="string">'$1zes'</span>],
  [<span class="regexp">/s$/gi</span>, <span class="string">'s'</span>],
  [<span class="regexp">/$/gi</span>, <span class="string">'s'</span>]
];
<span class="keyword">var</span> rules = exports.pluralization;</code></pre></div><p>These rules are applied while processing the argument to <code>toCollectionName</code>.</p><hr class=""></div><div class="item static public"><h3 id="utils_exports-uncountables"><a href="#utils_exports-uncountables">exports.uncountables</a></h3><p>Uncountable words.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">exports.uncountables = [
  <span class="string">'advice'</span>,
  <span class="string">'energy'</span>,
  <span class="string">'excretion'</span>,
  <span class="string">'digestion'</span>,
  <span class="string">'cooperation'</span>,
  <span class="string">'health'</span>,
  <span class="string">'justice'</span>,
  <span class="string">'labour'</span>,
  <span class="string">'machinery'</span>,
  <span class="string">'equipment'</span>,
  <span class="string">'information'</span>,
  <span class="string">'pollution'</span>,
  <span class="string">'sewage'</span>,
  <span class="string">'paper'</span>,
  <span class="string">'money'</span>,
  <span class="string">'species'</span>,
  <span class="string">'series'</span>,
  <span class="string">'rain'</span>,
  <span class="string">'rice'</span>,
  <span class="string">'fish'</span>,
  <span class="string">'sheep'</span>,
  <span class="string">'moose'</span>,
  <span class="string">'deer'</span>,
  <span class="string">'news'</span>
];
<span class="keyword">var</span> uncountables = exports.uncountables;</code></pre></div><p>These words are applied while processing the argument to <code>toCollectionName</code>.</p><hr class=""></div><div class="item static private"><h3 id="utils_exports-deepEqual"><a href="#utils_exports-deepEqual">exports.deepEqual(<code>a</code>, <code>b</code>)</a></h3><p>Determines if <code>a</code> and <code>b</code> are deep equal.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">exports.deepEqual = <span class="function"><span class="keyword">function</span> <span class="title">deepEqual</span> <span class="params">(a, b)</span> {</span>
  <span class="keyword">if</span> (a === b) <span class="keyword">return</span> <span class="literal">true</span>;

  <span class="keyword">if</span> (a <span class="keyword">instanceof</span> Date &amp;&amp; b <span class="keyword">instanceof</span> Date)
    <span class="keyword">return</span> a.getTime() === b.getTime();

  <span class="keyword">if</span> (a <span class="keyword">instanceof</span> ObjectId &amp;&amp; b <span class="keyword">instanceof</span> ObjectId) {
    <span class="keyword">return</span> a.toString() === b.toString();
  }

  <span class="keyword">if</span> (<span class="keyword">typeof</span> a !== <span class="string">'object'</span> &amp;&amp; <span class="keyword">typeof</span> b !== <span class="string">'object'</span>)
    <span class="keyword">return</span> a == b;

  <span class="keyword">if</span> (a === <span class="literal">null</span> || b === <span class="literal">null</span> || a === <span class="literal">undefined</span> || b === <span class="literal">undefined</span>)
    <span class="keyword">return</span> <span class="literal">false</span>

  <span class="keyword">if</span> (a.prototype !== b.prototype) <span class="keyword">return</span> <span class="literal">false</span>;

  <span class="comment">// Handle MongooseNumbers</span>
  <span class="keyword">if</span> (a <span class="keyword">instanceof</span> Number &amp;&amp; b <span class="keyword">instanceof</span> Number) {
    <span class="keyword">return</span> a.valueOf() === b.valueOf();
  }

  <span class="keyword">if</span> (Buffer.isBuffer(a)) {
    <span class="keyword">if</span> (!Buffer.isBuffer(b)) <span class="keyword">return</span> <span class="literal">false</span>;
    <span class="keyword">if</span> (a.length !== b.length) <span class="keyword">return</span> <span class="literal">false</span>;
    <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>, len = a.length; i &lt; len; ++i) {
      <span class="keyword">if</span> (a[i] !== b[i]) <span class="keyword">return</span> <span class="literal">false</span>;
    }
    <span class="keyword">return</span> <span class="literal">true</span>;
  }

  <span class="keyword">if</span> (isMongooseObject(a)) a = a.toObject();
  <span class="keyword">if</span> (isMongooseObject(b)) b = b.toObject();

  <span class="keyword">try</span> {
    <span class="keyword">var</span> ka = Object.keys(a),
        kb = Object.keys(b),
        key, i;
  } <span class="keyword">catch</span> (e) {<span class="comment">//happens when one is a string literal and the other isn't</span>
    <span class="keyword">return</span> <span class="literal">false</span>;
  }

  <span class="comment">// having the same number of owned properties (keys incorporates</span>
  <span class="comment">// hasOwnProperty)</span>
  <span class="keyword">if</span> (ka.length != kb.length)
    <span class="keyword">return</span> <span class="literal">false</span>;

  <span class="comment">//the same set of keys (although not necessarily the same order),</span>
  ka.sort();
  kb.sort();

  <span class="comment">//~~~cheap key test</span>
  <span class="keyword">for</span> (i = ka.length - <span class="number">1</span>; i >= <span class="number">0</span>; i--) {
    <span class="keyword">if</span> (ka[i] != kb[i])
      <span class="keyword">return</span> <span class="literal">false</span>;
  }

  <span class="comment">//equivalent values for every corresponding key, and</span>
  <span class="comment">//~~~possibly expensive deep test</span>
  <span class="keyword">for</span> (i = ka.length - <span class="number">1</span>; i >= <span class="number">0</span>; i--) {
    key = ka[i];
    <span class="keyword">if</span> (!deepEqual(a[key], b[key])) <span class="keyword">return</span> <span class="literal">false</span>;
  }

  <span class="keyword">return</span> <span class="literal">true</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>a</code><span class="types"> &lt;<a href="#any">any</a>&gt; </span><span>a value to compare to `b`</span></li><li><code>b</code><span class="types"> &lt;<a href="#any">any</a>&gt; </span><span>a value to compare to `a`</span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Boolean">Boolean</a>&gt; </span><span></span></li></ul></div><p>Modified from node/lib/assert.js</p><hr class="private"></div><div class="item static private"><h3 id="utils_exports-clone"><a href="#utils_exports-clone">exports.clone(<code>obj</code>, <code>options</code>)</a></h3><p>Object clone with Mongoose natives support.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">exports.clone = <span class="function"><span class="keyword">function</span> <span class="title">clone</span> <span class="params">(obj, options)</span> {</span>
  <span class="keyword">if</span> (obj === <span class="literal">undefined</span> || obj === <span class="literal">null</span>)
    <span class="keyword">return</span> obj;

  <span class="keyword">if</span> (Array.isArray(obj))
    <span class="keyword">return</span> cloneArray(obj, options);

  <span class="keyword">if</span> (isMongooseObject(obj)) {
    <span class="keyword">if</span> (options &amp;&amp; options.json &amp;&amp; <span class="string">'function'</span> === <span class="keyword">typeof</span> obj.toJSON) {
      <span class="keyword">return</span> obj.toJSON(options);
    } <span class="keyword">else</span> {
      <span class="keyword">return</span> obj.toObject(options);
    }
  }

  <span class="keyword">if</span> (<span class="string">'Object'</span> === obj.constructor.name)
    <span class="keyword">return</span> cloneObject(obj, options);

  <span class="keyword">if</span> (<span class="string">'Date'</span> === obj.constructor.name || <span class="string">'Function'</span> === obj.constructor.name)
    <span class="keyword">return</span> <span class="keyword">new</span> obj.constructor(+obj);

  <span class="keyword">if</span> (<span class="string">'RegExp'</span> === obj.constructor.name)
    <span class="keyword">return</span> <span class="keyword">new</span> RegExp(obj.source);

  <span class="keyword">if</span> (obj <span class="keyword">instanceof</span> ObjectId) {
    <span class="keyword">return</span> <span class="keyword">new</span> ObjectId(obj.id);
  }

  <span class="keyword">if</span> (obj.valueOf)
    <span class="keyword">return</span> obj.valueOf();
};
<span class="keyword">var</span> clone = exports.clone;</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>obj</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>the object to clone</span></li><li><code>options</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>the cloned object</span></li></ul></div><p>Creates a minimal data Object.<br />It does not clone empty Arrays, empty Objects, and undefined values.<br />This makes the data payload sent to MongoDB as minimal as possible.</p><hr class="private"></div><div class="item static private"><h3 id="utils_exports-options"><a href="#utils_exports-options">exports.options(<code>defaults</code>, <code>options</code>)</a></h3><p>Copies and merges options with defaults.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">exports.options = <span class="function"><span class="keyword">function</span> <span class="params">(defaults, options)</span> {</span>
  <span class="keyword">var</span> keys = Object.keys(defaults)
    , i = keys.length
    , k ;

  options = options || {};

  <span class="keyword">while</span> (i--) {
    k = keys[i];
    <span class="keyword">if</span> (!(k <span class="keyword">in</span> options)) {
      options[k] = defaults[k];
    }
  }

  <span class="keyword">return</span> options;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>defaults</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>options</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span>the merged object</span></li></ul></div><hr class="private"></div><div class="item static private"><h3 id="utils_exports-random"><a href="#utils_exports-random">exports.random()</a></h3><p>Generates a random string</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">exports.random = <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">return</span> Math.random().toString().substr(<span class="number">3</span>);
};</code></pre></div><hr class="private"></div><div class="item static private"><h3 id="utils_exports-merge"><a href="#utils_exports-merge">exports.merge(<code>to</code>, <code>from</code>)</a></h3><p>Merges <code>from</code> into <code>to</code> without overwriting existing properties.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">exports.merge = <span class="function"><span class="keyword">function</span> <span class="title">merge</span> <span class="params">(to, from)</span> {</span>
  <span class="keyword">var</span> keys = Object.keys(from)
    , i = keys.length
    , key

  <span class="keyword">while</span> (i--) {
    key = keys[i];
    <span class="keyword">if</span> (<span class="string">'undefined'</span> === <span class="keyword">typeof</span> to[key]) {
      to[key] = from[key];
    } <span class="keyword">else</span> {
      merge(to[key], from[key]);
    }
  }
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>to</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>from</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><hr class="private"></div><div class="item static private"><h3 id="utils_exports-args"><a href="#utils_exports-args">exports.args()</a></h3><p>A faster Array.prototype.slice.call(arguments) alternative</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">exports.args = <span class="function"><span class="keyword">function</span> <span class="params">(args, slice, sliceEnd)</span> {</span>
  <span class="keyword">var</span> ret = [];
  <span class="keyword">var</span> start = slice || <span class="number">0</span>;
  <span class="keyword">var</span> end = <span class="number">3</span> === arguments.length
    ? sliceEnd
    : args.length;

  <span class="keyword">for</span> (<span class="keyword">var</span> i = start; i &lt; end; ++i) {
    ret[i - start] = args[i];
  }

  <span class="keyword">return</span> ret;
}</code></pre></div><hr class="private"></div><div class="item static private"><h3 id="utils_exports-tick"><a href="#utils_exports-tick">exports.tick(<code>callback</code>)</a></h3><p>process.nextTick helper.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">exports.tick = <span class="function"><span class="keyword">function</span> <span class="title">tick</span> <span class="params">(callback)</span> {</span>
  <span class="keyword">if</span> (<span class="string">'function'</span> !== <span class="keyword">typeof</span> callback) <span class="keyword">return</span>;
  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
    <span class="keyword">try</span> {
      callback.apply(<span class="keyword">this</span>, arguments);
    } <span class="keyword">catch</span> (err) {
      <span class="comment">// only nextTick on err to get out of</span>
      <span class="comment">// the event loop and avoid state corruption.</span>
      process.nextTick(<span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
        <span class="keyword">throw</span> err;
      });
    }
  }
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>callback</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><p>Wraps <code>callback</code> in a try/catch + nextTick.</p>

<p>node-mongodb-native has a habit of state corruption when an error is immediately thrown from within a collection callback.</p><hr class="private"></div><div class="item static private"><h3 id="utils_exports-isMongooseObject"><a href="#utils_exports-isMongooseObject">exports.isMongooseObject(<code>v</code>)</a></h3><p>Returns if <code>v</code> is a mongoose object that has a <code>toObject()</code> method we can use.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">exports.isMongooseObject = <span class="function"><span class="keyword">function</span> <span class="params">(v)</span> {</span>
  Document || (Document = require(<span class="string">'./document'</span>));
  MongooseArray || (MongooseArray = require(<span class="string">'./types'</span>).Array);
  MongooseBuffer || (MongooseBuffer = require(<span class="string">'./types'</span>).Buffer);

  <span class="keyword">return</span> v <span class="keyword">instanceof</span> Document ||
         v <span class="keyword">instanceof</span> MongooseArray ||
         v <span class="keyword">instanceof</span> MongooseBuffer
}
<span class="keyword">var</span> isMongooseObject = exports.isMongooseObject;</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>v</code><span class="types"> &lt;<a href="#any">any</a>&gt; </span><span></span></li></ul></div><p>This is for compatibility with libs like Date.js which do foolish things to Natives.</p><hr class="private"></div><div class="item static private"><h3 id="utils_exports-expires"><a href="#utils_exports-expires">exports.expires(<code>object</code>)</a></h3><p>Converts <code>expires</code> options of index objects to <code>expiresAfterSeconds</code> options for MongoDB.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">exports.expires = <span class="function"><span class="keyword">function</span> <span class="title">expires</span> <span class="params">(object)</span> {</span>
  <span class="keyword">if</span> (!(object &amp;&amp; <span class="string">'Object'</span> == object.constructor.name)) <span class="keyword">return</span>;
  <span class="keyword">if</span> (!(<span class="string">'expires'</span> <span class="keyword">in</span> object)) <span class="keyword">return</span>;

  <span class="keyword">var</span> when;
  <span class="keyword">if</span> (<span class="string">'string'</span> != <span class="keyword">typeof</span> object.expires) {
    when = object.expires;
  } <span class="keyword">else</span> {
    when = Math.round(ms(object.expires) / <span class="number">1000</span>);
  }
  object.expiresAfterSeconds = when;
  <span class="keyword">delete</span> object.expires;
}

exports.readPref = <span class="function"><span class="keyword">function</span> <span class="title">readPref</span> <span class="params">(pref, tags)</span> {</span>
  <span class="keyword">if</span> (Array.isArray(pref)) {
    tags = pref[<span class="number">1</span>];
    pref = pref[<span class="number">0</span>];
  }

  <span class="keyword">switch</span> (pref) {
    <span class="keyword">case</span> <span class="string">'p'</span>:
      pref = <span class="string">'primary'</span>;
      <span class="keyword">break</span>;
    <span class="keyword">case</span> <span class="string">'pp'</span>:
      pref = <span class="string">'primaryPrefered'</span>;
      <span class="keyword">break</span>;
    <span class="keyword">case</span> <span class="string">'s'</span>:
      pref = <span class="string">'secondary'</span>;
      <span class="keyword">break</span>;
    <span class="keyword">case</span> <span class="string">'sp'</span>:
      pref = <span class="string">'secondaryPrefered'</span>;
      <span class="keyword">break</span>;
    <span class="keyword">case</span> <span class="string">'n'</span>:
      pref = <span class="string">'nearest'</span>;
      <span class="keyword">break</span>;
  }

  <span class="keyword">return</span> <span class="keyword">new</span> ReadPref(pref, tags);
}</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>object</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><hr class="private"></div></li><li class="module "><a href="https://github.com/LearnBoost/mongoose/tree/3.1.2/virtualtype.js" id="virtualtype-js">virtualtype.js</a><div class="item method public"><h3 id="virtualtype_VirtualType"><a href="#virtualtype_VirtualType">VirtualType()</a></h3><p>VirtualType constructor</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript"><span class="function"><span class="keyword">function</span> <span class="title">VirtualType</span> <span class="params">(options, name)</span> {</span>
  <span class="keyword">this</span>.path = name;
  <span class="keyword">this</span>.getters = [];
  <span class="keyword">this</span>.setters = [];
  <span class="keyword">this</span>.options = options || {};
}</code></pre></div><div class="description"><p>This is what mongoose uses to define virtual attributes via <code>Schema.prototype.virtual</code>.</p>

<h4>Example:</h4>

<pre><code><span class="keyword">var</span> fullname = schema.virtual(<span class="string">'fullname'</span>);
fullname <span class="keyword">instanceof</span> mongoose.VirtualType <span class="comment">// true</span></code></pre></div><hr class=""></div><div class="item method public"><h3 id="virtualtype_VirtualType-get"><a href="#virtualtype_VirtualType-get">VirtualType#get(<code>fn</code>)</a></h3><p>Defines a getter.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">VirtualType.prototype.get = <span class="function"><span class="keyword">function</span> <span class="params">(fn)</span> {</span>
  <span class="keyword">this</span>.getters.push(fn);
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>fn</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#virtualtype_VirtualType">VirtualType</a>&gt; </span><span>this</span></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code><span class="keyword">var</span> virtual = schema.virtual(<span class="string">'fullname'</span>);
virtual.get(<span class="function"><span class="keyword">function</span> <span class="params">()</span> {</span>
  <span class="keyword">return</span> <span class="keyword">this</span>.name.first + <span class="string">' '</span> + <span class="keyword">this</span>.name.last;
});</code></pre></div><hr class=""></div><div class="item method public"><h3 id="virtualtype_VirtualType-set"><a href="#virtualtype_VirtualType-set">VirtualType#set(<code>fn</code>)</a></h3><p>Defines a setter.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">VirtualType.prototype.set = <span class="function"><span class="keyword">function</span> <span class="params">(fn)</span> {</span>
  <span class="keyword">this</span>.setters.push(fn);
  <span class="keyword">return</span> <span class="keyword">this</span>;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>fn</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function">Function</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#virtualtype_VirtualType">VirtualType</a>&gt; </span><span>this</span></li></ul></div><div class="description"><h4>Example:</h4>

<pre><code><span class="keyword">var</span> virtual = schema.virtual(<span class="string">'fullname'</span>);
virtual.set(<span class="function"><span class="keyword">function</span> <span class="params">(v)</span> {</span>
  <span class="keyword">var</span> parts = v.split(<span class="string">' '</span>);
  <span class="keyword">this</span>.name.first = parts[<span class="number">0</span>];
  <span class="keyword">this</span>.name.last = parts[<span class="number">1</span>];
});</code></pre></div><hr class=""></div><div class="item method public"><h3 id="virtualtype_VirtualType-applyGetters"><a href="#virtualtype_VirtualType-applyGetters">VirtualType#applyGetters(<code>value</code>, <code>scope</code>)</a></h3><p>Applies getters to <code>value</code> using optional <code>scope</code>.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">VirtualType.prototype.applyGetters = <span class="function"><span class="keyword">function</span> <span class="params">(value, scope)</span> {</span>
  <span class="keyword">var</span> v = value;
  <span class="keyword">for</span> (<span class="keyword">var</span> l = <span class="keyword">this</span>.getters.length - <span class="number">1</span>; l >= <span class="number">0</span>; l--) {
    v = <span class="keyword">this</span>.getters[l].call(scope, v, <span class="keyword">this</span>);
  }
  <span class="keyword">return</span> v;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>value</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>scope</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#any">any</a>&gt; </span><span>the value after applying all getters</span></li></ul></div><div class="description"></div><hr class=""></div><div class="item method public"><h3 id="virtualtype_VirtualType-applySetters"><a href="#virtualtype_VirtualType-applySetters">VirtualType#applySetters(<code>value</code>, <code>scope</code>)</a></h3><p>Applies setters to <code>value</code> using optional <code>scope</code>.</p><span class="showcode">show code</span><div class="sourcecode"><pre><code class="javascript">VirtualType.prototype.applySetters = <span class="function"><span class="keyword">function</span> <span class="params">(value, scope)</span> {</span>
  <span class="keyword">var</span> v = value;
  <span class="keyword">for</span> (<span class="keyword">var</span> l = <span class="keyword">this</span>.setters.length - <span class="number">1</span>; l >= <span class="number">0</span>; l--) {
    v = <span class="keyword">this</span>.setters[l].call(scope, v, <span class="keyword">this</span>);
  }
  <span class="keyword">return</span> v;
};</code></pre></div><div class="params"><h4>Parameters:</h4><ul><li><code>value</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li><li><code>scope</code><span class="types"> &lt;<a href="https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object">Object</a>&gt; </span><span></span></li></ul></div><div class="returns"><h4>Returns:</h4><ul><li><span class="types"> &lt;<a href="#any">any</a>&gt; </span><span>the value after applying all setters</span></li></ul></div><div class="description"></div><hr class=""></div></li></ul></div><script>document.body.className = 'load';</script><script>var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-1122274-9']);
_gaq.push(['_trackPageview']);

(function() {
  var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
  ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
  var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();</script><script src="./js/zepto.min.js"></script><script>$(".module").on("click", ".showcode", function (e) {
  $(this).closest(".item").find(".sourcecode").first().toggle();
});
$("#content .controls input").on("click", function (e) {
  $(".private").toggle()
})</script></body></html>
